Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
49 changes: 0 additions & 49 deletions content/en/guide/v10/differences-to-react.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,55 +169,6 @@ Ultimately, if you're looking at the generated output code for a Preact applicat

The legacy `Context` API requires Components to declare specific properties using React's `contextTypes` or `childContextTypes` in order to receive those values. Preact does not have this requirement: all Components receive all `context` properties produced by `getChildContext()` by default.

## Features exclusive to `preact/compat`

`preact/compat` is our **compat**ibility layer that translates React code to Preact. For existing React users this can be an easy way to try out Preact without changing any of your code, by [setting up a few aliases](/guide/v10/getting-started#aliasing-react-to-preact) in your bundler configuration.

### Children API

The `Children` API is a specialized set of methods for working with the value of `props.children`. For Preact this is generally unnecessary, and we recommend using the built-in array methods instead. In Preact, `props.children` is either a Virtual DOM node, an empty value like `null`, or an Array of Virtual DOM nodes. The first two cases are the simplest and most common, since it's possible to use or return `children` as-is:

```jsx
// React:
function App(props) {
return <Modal content={Children.only(props.children)} />;
}

// Preact: use props.children directly:
function App(props) {
return <Modal content={props.children} />;
}
```

For specialized cases where you need to iterate over the children passed to a component, Preact provides a `toChildArray()` method that accepts any `props.children` value and returns a flattened and normalized Array of Virtual DOM nodes.

```jsx
// React
function App(props) {
const cols = Children.count(props.children);
return <div data-columns={cols}>{props.children}</div>;
}

// Preact
function App(props) {
const cols = toChildArray(props.children).length;
return <div data-columns={cols}>{props.children}</div>;
}
```

A React-compatible `Children` API is available from `preact/compat` to make integration with existing component libraries seamless.

### Specialised Components

[preact/compat] ships with specialised components that are not necessary for every app. These include

- [PureComponent](/guide/v10/switching-to-preact#purecomponent): Only updates if `props` or `state` have changed
- [memo](/guide/v10/switching-to-preact#memo): Similar in spirit to `PureComponent` but allows to use a custom comparison function
- [forwardRef](/guide/v10/switching-to-preact#forwardref): Supply a `ref` to a specified child component.
- [Portals](/guide/v10/switching-to-preact#portals): Continues rendering the current tree into a different DOM container
- [Suspense](/guide/v10/switching-to-preact#suspense-experimental): **experimental** Allows to display fallback content in case the tree is not ready
- [lazy](/guide/v10/switching-to-preact#suspense-experimental): **experimental** Lazy load async code and mark a tree as ready/not ready accordingly.

[project goals]: /about/project-goals
[hyperscript]: https://github.com/dominictarr/hyperscript
[preact/compat]: /guide/v10/switching-to-preact
Expand Down
49 changes: 0 additions & 49 deletions content/en/guide/v11/differences-to-react.md
Original file line number Diff line number Diff line change
Expand Up @@ -169,55 +169,6 @@ Ultimately, if you're looking at the generated output code for a Preact applicat

The legacy `Context` API requires Components to declare specific properties using React's `contextTypes` or `childContextTypes` in order to receive those values. Preact does not have this requirement: all Components receive all `context` properties produced by `getChildContext()` by default.

## Features exclusive to `preact/compat`

`preact/compat` is our **compat**ibility layer that translates React code to Preact. For existing React users this can be an easy way to try out Preact without changing any of your code, by [setting up a few aliases](/guide/v10/getting-started#aliasing-react-to-preact) in your bundler configuration.

### Children API

The `Children` API is a specialized set of methods for working with the value of `props.children`. For Preact this is generally unnecessary, and we recommend using the built-in array methods instead. In Preact, `props.children` is either a Virtual DOM node, an empty value like `null`, or an Array of Virtual DOM nodes. The first two cases are the simplest and most common, since it's possible to use or return `children` as-is:

```jsx
// React:
function App(props) {
return <Modal content={Children.only(props.children)} />;
}

// Preact: use props.children directly:
function App(props) {
return <Modal content={props.children} />;
}
```

For specialized cases where you need to iterate over the children passed to a component, Preact provides a `toChildArray()` method that accepts any `props.children` value and returns a flattened and normalized Array of Virtual DOM nodes.

```jsx
// React
function App(props) {
const cols = Children.count(props.children);
return <div data-columns={cols}>{props.children}</div>;
}

// Preact
function App(props) {
const cols = toChildArray(props.children).length;
return <div data-columns={cols}>{props.children}</div>;
}
```

A React-compatible `Children` API is available from `preact/compat` to make integration with existing component libraries seamless.

### Specialised Components

[preact/compat] ships with specialised components that are not necessary for every app. These include

- [PureComponent](/guide/v10/switching-to-preact#purecomponent): Only updates if `props` or `state` have changed
- [memo](/guide/v10/switching-to-preact#memo): Similar in spirit to `PureComponent` but allows to use a custom comparison function
- [forwardRef](/guide/v10/switching-to-preact#forwardref): Supply a `ref` to a specified child component.
- [Portals](/guide/v10/switching-to-preact#portals): Continues rendering the current tree into a different DOM container
- [Suspense](/guide/v10/switching-to-preact#suspense-experimental): **experimental** Allows to display fallback content in case the tree is not ready
- [lazy](/guide/v10/switching-to-preact#suspense-experimental): **experimental** Lazy load async code and mark a tree as ready/not ready accordingly.

[project goals]: /about/project-goals
[hyperscript]: https://github.com/dominictarr/hyperscript
[preact/compat]: /guide/v10/switching-to-preact
Expand Down
33 changes: 0 additions & 33 deletions content/ja/guide/v10/differences-to-react.md
Original file line number Diff line number Diff line change
Expand Up @@ -156,39 +156,6 @@ React.createElement(
Reactの古いコンテキストAPIではコンポーネントに`contextTypes`もしくは`childContextTypes`を実装する必要があります。
Preactではこの制限はありません。すべてのコンポーネントは`getChildContext()`から生成されたすべての`context`の値を受け取ります。

## `preact`には無くて`preact/compat`にある機能

`preact/compat`はReactのコードをPreactに移行するための**互換**レイヤーです。
既存のReactユーザはコードはそのままでバンドラの設定にいくつかのエイリアスをセットするだけで、とても手軽にPreactを試すことができます。

### Children API

Reactの`Children`APIはコンポーネントの`children`を反復処理するためのAPIです。
PreactではこのAPIは必要ありません。代わりにネイティブの配列のメソッドを使うことを推奨します。

```jsx
// React
function App(props) {
return <div>{Children.count(props.children)}</div>
}

// Preact: 子コンポーネントを配列に変換します。配列の標準のプロパティを使います。
function App(props) {
return <div>{toChildArray(props.children).length}</div>
}
```

### 固有のコンポーネントと関数

[preact/compat]は以下のような特殊な用途で使用することを目的としたコンポーネントや関数を提供しています。

- [PureComponent](/guide/v10/switching-to-preact#purecomponent): `props`もしくは`state`が変化した場合のみ更新されます。
- [memo](/guide/v10/switching-to-preact#memo): `PureComponent`と用途が似ていますがこちらは比較のための関数を指定することができます。
- [forwardRef](/guide/v10/switching-to-preact#forwardRef): 指定した子コンポーネントに`ref`をセットします。
- [Portals](/guide/v10/switching-to-preact#portals): 指定した仮想DOMツリーを別のDOMコンテナにレンダリングします。
- [Suspense](/guide/v10/switching-to-preact#suspense): **実験的機能** 仮想DOMツリーの準備ができていない間は代替の仮想DOMツリーのレンダリングすることを可能にします。
- [lazy](/guide/v10/switching-to-preact#suspense): **実験的機能** 非同期のコードを遅延ロードします。そして、ロード完了を通知します。

[Projectの目的]: /about/project-goals
[hyperscript]: https://github.com/dominictarr/hyperscript
[preact/compat]: /guide/v10/switching-to-preact
Expand Down
49 changes: 0 additions & 49 deletions content/kr/guide/v10/differences-to-react.md
Original file line number Diff line number Diff line change
Expand Up @@ -168,55 +168,6 @@ React.createElement(

레거시 `Context` API는 컴포넌트가 해당 값을 받기 위해 React의 `contextTypes`나 `childContextTypes`를 사용해 특정 프로퍼티를 선언해야 합니다. 하지만 Preact는 그럴 필요가 없습니다. 모든 컴포넌트는 기본적으로 `getChildContext()`를 통해 만들어진 모든 `context` 프로퍼티를 전달받습니다.

## `preact/compat` 전용 기능

`preact/compat` 는 React 코드를 Preact로 번역해주는 Preact의 호환성 레이어(**compat**ibility layer)입니다. React 사용자가 코드를 수정하지 않고 Preact를 시도해볼 수 있는 쉬운 방법입니다. 번들러 환경 설정에 [몇가지 별칭을 세팅](/guide/v10/getting-started#aliasing-react-to-preact)하면 됩니다.

### Children API

`Children` API는 `props.children`의 값을 사용하기 위해 전문화된 메소드의 집합입니다. Preact에서는 일반적으로 불필요하며, 대신 내장 배열 메소드를 사용하기를 권장합니다. Preact에서 `props.children`은 Virtual DOM 노드나 `null`과 같은 빈값 또는 Virtual DOM node 배열입니다. 아래 두 경우는 `children`을 있는 그대로 사용하거나 리턴할 수 있기 때문에 가장 간단하고 흔한 경우입니다.

```jsx
// React:
function App(props) {
return <Modal content={Children.only(props.children)} />
}

// Preact : props.children 바로 사용:
function App(props) {
return <Modal content={props.children} />
}
```

컴포넌트에 전달된 children을 반복해야 하는 특수한 경우를 위해 Preact는 `toChildArray()` 메소드를 제공합니다. `toChildArray()`는 어떠한 `props.children` 값이라도 전달받고 또한 평평하고(Flatten) 정규화된 Virtual DOM 노드 배열을 리턴합니다.

```jsx
// React
function App(props) {
const cols = Children.count(props.children);
return <div data-columns={cols}>{props.children}</div>
}

// Preact
function App(props) {
const cols = toChildArray(props.children).length;
return <div data-columns={cols}>{props.children}</div>
}
```

React와 호환되는 `Children` API는 `preact/compat`에서 제공되며 기존의 컴포넌트 라이브러리와 원활하게 통합할 수 있습니다.

### 특수한 목적의 컴포넌트

[preact/compat]는 모든 앱에서 필요하지는 않은 특수한 컴포넌트들도 포함하여 제공합니다.

- [PureComponent](/guide/v10/switching-to-preact#purecomponent): `props`나 `state`가 변경되었을 때만 업데이트합니다.
- [memo](/guide/v10/switching-to-preact#memo): `PureComponent`와 유사하지만, 사용자 정의 비교 함수를 사용할 수 있습니다.
- [forwardRef](/guide/v10/switching-to-preact#forwardRef): 명시된 자식 컴포넌트에 `ref`를 전달할 수 있습니다.
- [Portals](/guide/v10/switching-to-preact#portals): 다른 DOM 컨테이너에 현재 트리를 계속해서 렌더링합니다.
- [Suspense](/guide/v10/switching-to-preact#suspense): **실험 단계** 트리가 준비되지 않은 경우 fallback 컨텐츠를 보여줍니다.
- [lazy](/guide/v10/switching-to-preact#suspense): **실험 단계** 비동기 코드를 느리게(Lazy) 로드하고 트리를 준비됨/준비되지 않음 상태로 표시합니다.

[Project Goals]: /about/project-goals
[hyperscript]: https://github.com/dominictarr/hyperscript
[preact/compat]: /guide/v10/switching-to-preact
Expand Down
31 changes: 0 additions & 31 deletions content/pt-br/guide/v10/differences-to-react.md
Original file line number Diff line number Diff line change
Expand Up @@ -117,37 +117,6 @@ Na maioria dos aplicativos Preact, você encontrará `h ()`, mas suportamos ambo

A API legada `Context` exige que os Componentes implementem `contextTypes` ou `childContextTypes` no React. Com Preact, não temos essa limitação e todos os componentes recebem todas as entradas do `context`, extraídas de `getChildContext ()`.

## Funcionalidades exclusivas para `preact / compat`

`preact/compat` é a nossa camada **compat** ibilidade que traduz o código React para Preact. Para usuários existentes do React, é muito fácil experimentar o Preact apenas configurando alguns aliases na configuração do empacotador e deixando o restante do código como está.

### Children-API

A API `Children` é uma maneira especializada de iterar sobre os `children` de um componente. Para Preact, essa API não é necessária e recomendamos o uso dos métodos de arrays nativos.

```jsx
// React
function App(props) {
return <div>{Children.count(props.children)}</div>
}

// Preact: Converta filhos em um array e use métodos de arrays padrão.
function App(props) {
return <div>{toChildArray(props.children).length}</div>
}
```

### Componentes especializados

[preact/compat] é fornecido com componentes especializados que não são necessários para todos os aplicativos. Esses incluem

- [PureComponent](/guide/v10/switching-to-preact#purecomponent): Atualiza somente se `props` e `state` foram alterados
- [memo](/guide/v10/switching-to-preact#memo): Semelhante em espírito ao `PureComponent`, mas permite usar uma função de comparação personalizada
- [forwardRef](/guide/v10/switching-to-preact#forwardRef): Forneça um `ref` para um componente filho especificado.
- [Portals](/guide/v10/switching-to-preact#portals): Continua renderizando a árvore atual em um contêiner DOM diferente
- [Suspense](/guide/v10/switching-to-preact#suspense): **experimental** Permite exibir o conteúdo de fallback caso a árvore não esteja pronta
- [lazy](/guide/v10/switching-to-preact#suspense): **experimental** Carregue o código assíncrono lazy e marque uma árvore como pronta / não pronta de acordo.

[Objetivos do projeto]: /about/project-goals
[hyperscript]: https://github.com/dominictarr/hyperscript
[preact/compat]: /guide/v10/switching-to-preact
Expand Down
49 changes: 0 additions & 49 deletions content/ru/guide/v10/differences-to-react.md
Original file line number Diff line number Diff line change
Expand Up @@ -165,55 +165,6 @@ React.createElement('a', { href: '/' }, React.createElement('span', null, 'Гл

Устаревший API `Context` требует, чтобы компоненты объявляли определённые свойства, используя `contextTypes` или `childContextTypes` React, чтобы получить эти значения. У Preact нет этого требования: все компоненты по умолчанию получают все свойства `context`, созданные `getChildContext()`.

## Возможности, эксклюзивные для `preact/compat`

`preact/compat` — это наш **уровень** совместимости, который преобразует код React в Preact. Для существующих пользователей React это может быть простой способ опробовать Preact, не меняя никакого кода, путём [установки нескольких псевдонимов](/guide/v10/getting-started#псевдонимы-react-для-preact) в конфигурации вашего сборщика.

### Children API

API `Children` — это специализированный набор методов для работы со значением `props.children`. Для Preact в этом обычно нет необходимости, и вместо этого мы рекомендуем использовать встроенные методы массива. В Preact `props.children` — это либо узел Virtual DOM, пустое значение, например `null`, либо массив узлов Virtual DOM. Первые два случая являются самыми простыми и распространёнными, поскольку можно использовать или возвращать `children` как есть:

```jsx
// React:
function App(props) {
return <Modal content={Children.only(props.children)} />;
}

// Preact: используйте props.children напрямую:
function App(props) {
return <Modal content={props.children} />;
}
```

Для специальных случаев, когда необходимо перебирать дочерние элементы, переданные компоненту, в Preact предусмотрен метод `toChildArray()`, который принимает любое значение `props.children` и возвращает сглаженный и нормализованный массив узлов Virtual DOM.

```jsx
// React
function App(props) {
const cols = Children.count(props.children);
return <div data-columns={cols}>{props.children}</div>;
}

// Preact
function App(props) {
const cols = toChildArray(props.children).length;
return <div data-columns={cols}>{props.children}</div>;
}
```

Из `preact/compat` доступен React-совместимый API `Children`, позволяющий без проблем интегрироваться с существующими библиотеками компонентов.

### Специализированные компоненты

[preact/compat] поставляется со специализированными компонентами, которые необходимы не для всех приложений. К ним относятся

- [PureComponent](/guide/v10/switching-to-preact#purecomponent): Обновление происходит только в том случае, если изменились `props` или `state`.
- [memo](/guide/v10/switching-to-preact#memo): Аналогичен `PureComponent`, но позволяет использовать пользовательскую функцию сравнения.
- [forwardRef](/guide/v10/switching-to-preact#forwardref): Применение `ref` к указанному дочернему компоненту.
- [Portals](/guide/v10/switching-to-preact#portals): Продолжает рендеринг текущего дерева в другой контейнер DOM.
- [Suspense](/guide/v10/switching-to-preact#suspense-experimental): **экспериментально** Позволяет отображать резервный контент, если дерево не готово.
- [lazy](/guide/v10/switching-to-preact#suspense-experimental): **экспериментально** Отложенная загрузка асинхронного кода и пометка дерева как готового/неготового соответственно.

[Project Goals]: /about/project-goals
[hyperscript]: https://github.com/dominictarr/hyperscript
[preact/compat]: /guide/v10/switching-to-preact
Expand Down
Loading