Skip to content

Translate "Forwarding refs" page #159

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Closed
wants to merge 10 commits into from
Closed
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
70 changes: 38 additions & 32 deletions content/docs/forwarding-refs.md
Original file line number Diff line number Diff line change
@@ -1,76 +1,82 @@
---
id: forwarding-refs
title: Forwarding Refs
title: Przekazywanie referencji
permalink: docs/forwarding-refs.html
---

Ref forwarding is a technique for automatically passing a [ref](/docs/refs-and-the-dom.html) through a component to one of its children. This is typically not necessary for most components in the application. However, it can be useful for some kinds of components, especially in reusable component libraries. The most common scenarios are described below.
Przekazywanie referencji (ang. *ref forwarding*) to technika, w której [referencję](/docs/refs-and-the-dom.html)
do komponentu "podajemy dalej" do jego dziecka. Dla większości komponentów w aplikacji nie jest to potrzebne,
jednak może okazać się przydatne w niektórych przypadkach, zwłaszcza w bibliotekach udostępniających uniwersalne komponenty.
Najczęstsze scenariusze opisujemy poniżej.

## Forwarding refs to DOM components {#forwarding-refs-to-dom-components}
## Przekazywanie referencji do komponentów DOM {#forwarding-refs-to-dom-components}

Consider a `FancyButton` component that renders the native `button` DOM element:
Rozważmy komponent `FancyButton`, który renderuje natywny element DOM - przycisk:
`embed:forwarding-refs/fancy-button-simple.js`

React components hide their implementation details, including their rendered output. Other components using `FancyButton` **usually will not need to** [obtain a ref](/docs/refs-and-the-dom.html) to the inner `button` DOM element. This is good because it prevents components from relying on each other's DOM structure too much.
Komponenty reactowe ukrywają szczegóły swojej implementacji, w tym także wyrenderowany HTML.
Inne komponenty używające `FancyButton` **z reguły nie potrzebują** [mieć dostępu do referencji](/docs/refs-and-the-dom.html) do wewnętrznego elementu `button`.
Jest to korzystne, gdyż zapobiega sytuacji, w której komponenty są za bardzo uzależnione od struktury drzewa DOM innych komponentów.

Although such encapsulation is desirable for application-level components like `FeedStory` or `Comment`, it can be inconvenient for highly reusable "leaf" components like `FancyButton` or `MyTextInput`. These components tend to be used throughout the application in a similar manner as a regular DOM `button` and `input`, and accessing their DOM nodes may be unavoidable for managing focus, selection, or animations.
Taka enkapsulacja jest pożądana na poziomie aplikacji, w komponentach takich jak `FeedStory` czy `Comment`. Natomiast może się okazać to niewygodne w przypadku komponentów wielokrotnego użytku, będących "liśćmi" drzewa. Np. `FancyButton` albo `MyTextInput`. Takie komponenty często używane są w wielu miejscach aplikacji, w podobny sposób jak zwyczajne elementy DOM typu `button` i `input`. W związku z tym, bezpośredni dostęp do ich DOM może okazać się konieczy, aby obsłużyć np. fokus, zaznaczenie czy animacje.

**Ref forwarding is an opt-in feature that lets some components take a `ref` they receive, and pass it further down (in other words, "forward" it) to a child.**
**Przekazywanie referencji jest opcjonalną funkcjonalnością, która pozwala komponentom wziąć przekazaną do nich referencję i "podać ją dalej" do swojego dziecka.**

In the example below, `FancyButton` uses `React.forwardRef` to obtain the `ref` passed to it, and then forward it to the DOM `button` that it renders:
W poniższym przykładzie `FancyButton` używa `React.forwardRef`, by przejąć przekazaną do niego referencję i przekazać ją dalej do elementu `button`, który renderuje:

`embed:forwarding-refs/fancy-button-simple-ref.js`

This way, components using `FancyButton` can get a ref to the underlying `button` DOM node and access it if necessary—just like if they used a DOM `button` directly.
Tym sposobem komponenty używające `FancyButton` mają referencję do elementu `button` znajdującego się wewnątrz. Mogą więc, w razie potrzeby, operować na komponencie tak, jakby operowały bezpośrednio na natywnym elemencie DOM.

Here is a step-by-step explanation of what happens in the above example:
Oto wyjaśnienie krok po kroku, opisujące, co wydarzyło się w przykładzie powyżej:

1. We create a [React ref](/docs/refs-and-the-dom.html) by calling `React.createRef` and assign it to a `ref` variable.
1. We pass our `ref` down to `<FancyButton ref={ref}>` by specifying it as a JSX attribute.
1. React passes the `ref` to the `(props, ref) => ...` function inside `forwardRef` as a second argument.
1. We forward this `ref` argument down to `<button ref={ref}>` by specifying it as a JSX attribute.
1. When the ref is attached, `ref.current` will point to the `<button>` DOM node.
1. Tworzymy [referencję reactową](/docs/refs-and-the-dom.html) wywołując `React.createRef` i przypisujemy ją do stałej `ref`.
1. Przekazujemy `ref` do `<FancyButton ref={ref}>` przypisując ją do atrybutu JSX.
1. Wewnątrz `forwardRef` React przekazuje `ref` do funkcji `(props, ref) => ...` jako drugi argument.
1. Podajemy argument `ref` dalej do `<button ref={ref}>` przypisując go do atrybutu JSX.
1. Gdy referencja zostanie zamontowana, `ref.current` będzie wskazywać na element DOM `<button>`.

>Note
>Uwaga
>
>The second `ref` argument only exists when you define a component with `React.forwardRef` call. Regular function or class components don't receive the `ref` argument, and ref is not available in props either.
>Drugi argument `ref` istnieje tylko, gdy definiujesz komponent przy pomocy wywołania `React.forwardRef`. Zwyczajna funkcja lub klasa nie dostanie argumentu `ref`, nawet jako jednej z właściwości (`props`).
>
>Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.
>Przekazywanie referencji nie jest ograniczone do elementów drzewa DOM. Możesz także przekazywać referencje do instancji komponentów klasowych.

## Note for component library maintainers {#note-for-component-library-maintainers}
## Uwaga dla autorów bibliotek komponentów {#note-for-component-library-maintainers}

**When you start using `forwardRef` in a component library, you should treat it as a breaking change and release a new major version of your library.** This is because your library likely has an observably different behavior (such as what refs get assigned to, and what types are exported), and this can break apps and other libraries that depend on the old behavior.
**Kiedy zaczniesz używać `forwardRef` w swojej bibliotece komponentów, potraktuj to jako zmianę krytyczną (ang. *breaking change*). W efekcie biblioteka powinna zostać wydana w nowej "wersji głównej" (ang. *major version*, *major release*).** Należy tak postąpić, ponieważ najprawdopodobniej twoja biblioteka zauważalnie zmieniła zachowanie (np. inaczej przypinając referencje i eksportując inne typy). Może to popsuć działanie aplikacji, które są zależne od dawnego zachowania.

Conditionally applying `React.forwardRef` when it exists is also not recommended for the same reasons: it changes how your library behaves and can break your users' apps when they upgrade React itself.
Stosowanie `React.forwardRef` warunkowo, gdy ono istnieje, także nie jest zalecane z tego samego powodu: zmienia to zachowanie biblioteki i może zepsuć działanie aplikacji użytkowników, gdy zmienią wersję Reacta.

## Forwarding refs in higher-order components {#forwarding-refs-in-higher-order-components}
## Przekazywanie referencji w komponentach wyższego rzędu {#forwarding-refs-in-higher-order-components}

Omawiana technika może okazać się wyjątkowo przydatna w [komponentach wyższego rzędu](/docs/higher-order-components.html) (KWR; ang. *Higher-Order Components* lub *HOC*). Zacznijmy od przykładu KWR-a, który wypisuje w konsoli wszystkie właściwości komponentu:

This technique can also be particularly useful with [higher-order components](/docs/higher-order-components.html) (also known as HOCs). Let's start with an example HOC that logs component props to the console:
`embed:forwarding-refs/log-props-before.js`

The "logProps" HOC passes all `props` through to the component it wraps, so the rendered output will be the same. For example, we can use this HOC to log all props that get passed to our "fancy button" component:
KWR `logProps` przekazuje wszystkie atrybuty do komponentu, który opakowuje, więc wyrenderowany wynik będzie taki sam. Na przykład, możemy użyć tego KWRa do logowania atrybutów, które zostaną przekazane do naszego komponentu `FancyButton`:
`embed:forwarding-refs/fancy-button.js`

There is one caveat to the above example: refs will not get passed through. That's because `ref` is not a prop. Like `key`, it's handled differently by React. If you add a ref to a HOC, the ref will refer to the outermost container component, not the wrapped component.
Powyższe rozwiązanie ma jeden minus: referencje nie zostaną przekazane do komponentu. Dzieje się tak, ponieważ `ref` nie jest atrybutem. Tak jak `key`, jest on obsługiwany przez Reacta w inny sposób. Referencja będzie w tym wypadku odnosiła się do najbardziej zewnętrznego kontenera, a nie do opakowanego komponentu.

This means that refs intended for our `FancyButton` component will actually be attached to the `LogProps` component:
Oznacza to, że referencje przeznaczone dla naszego komponentu `FancyButton` będą w praktyce wskazywać na komponent `LogProps`.
`embed:forwarding-refs/fancy-button-ref.js`

Fortunately, we can explicitly forward refs to the inner `FancyButton` component using the `React.forwardRef` API. `React.forwardRef` accepts a render function that receives `props` and `ref` parameters and returns a React node. For example:
Na szczęście możemy jawnie przekazać referencję do wewnętrznego komponentu `FancyButton` używając API `React.forwardRef`. `React.forwardRef` przyjmuje funkcję renderującą, która otrzymuje parametry `props` oraz `ref`, a zwraca element reactowy. Na przykład:
`embed:forwarding-refs/log-props-after.js`

## Displaying a custom name in DevTools {#displaying-a-custom-name-in-devtools}
## Wyświetlanie własnej nazwy w narzędziach deweloperskich {#displaying-a-custom-name-in-devtools}

`React.forwardRef` accepts a render function. React DevTools uses this function to determine what to display for the ref forwarding component.
`React.forwardRef` przyjmuje funkcję renderującą. Narzędzia deweloperskie Reacta (ang. *React DevTools*) używają tej funkcji do określenia, jak wyświetlać komponent, który przekazuje referencję.

For example, the following component will appear as "*ForwardRef*" in the DevTools:
Przykładowo, następujący komponent w narzędziach deweloperskich wyświetli się jako "*ForwardRef*":

`embed:forwarding-refs/wrapped-component.js`

If you name the render function, DevTools will also include its name (e.g. "*ForwardRef(myFunction)*"):
Jeśli nazwiesz funkcję renderującą, narzędzia deweloperskie uwzględnią tę nazwę (np. "*ForwardRef(myFunction)*"):

`embed:forwarding-refs/wrapped-component-with-function-name.js`

You can even set the function's `displayName` property to include the component you're wrapping:
Możesz nawet ustawić właściwość `displayName` funkcji tak, aby uwzględniała nazwę opakowanego komponentu:

`embed:forwarding-refs/customized-display-name.js`
48 changes: 26 additions & 22 deletions content/warnings/dont-call-proptypes.md
Original file line number Diff line number Diff line change
Expand Up @@ -4,47 +4,48 @@ layout: single
permalink: warnings/dont-call-proptypes.html
---

> Note:
> Uwaga:
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Ten plik nie powinien się tu znaleźć. Wygląda na to, że nie zaktualizowałeś brancha przed stworzeniem kolejnego. Wyrzuć go, bo nie chcę mi się go drugi raz sprawdzać ;)

>
> `React.PropTypes` has moved into a different package since React v15.5. Please use [the `prop-types` library instead](https://www.npmjs.com/package/prop-types).
> Z wersją React v15.5 `React.PropTypes` zostało przeniesione do innej paczki. Zamiast importować z paczki Reacta, używaj [biblioteki `prop-types`](https://www.npmjs.com/package/prop-types).
>
>We provide [a codemod script](/blog/2017/04/07/react-v15.5.0.html#migrating-from-react.proptypes) to automate the conversion.
> Dla ułatwienia migracji przygotowaliśmy [skrypt codemod](/blog/2017/04/07/react-v15.5.0.html#migrating-from-react.proptypes).

In a future major release of React, the code that implements PropType validation functions will be stripped in production. Once this happens, any code that calls these functions manually (that isn't stripped in production) will throw an error.
W przyszłych wersjach Reacta kod, który implementuje funkcje walidujące PropTypes będzie wycinany na produkcji. Gdy to nastąpi, każdy kod wywoujący te funkcje bezpośrednio będzie powodował błąd (o ile także nie zostanie wycięty na produkcji).

### Declaring PropTypes is still fine {#declaring-proptypes-is-still-fine}
### Nadal można deklarować Proptypes w tradycyjny sposób {#declaring-proptypes-is-still-fine}

The normal usage of PropTypes is still supported:
Typowe użycie PropTypes wciąż jest wspierane:

```javascript
Button.propTypes = {
highlighted: PropTypes.bool
};
```

Nothing changes here.
Tutaj nic się nie zmienia.

### Don’t call PropTypes directly {#dont-call-proptypes-directly}
### Nie wywołuj PropTypes bezpośrednio {#dont-call-proptypes-directly}

Using PropTypes in any other way than annotating React components with them is no longer supported:
Używanie PropTypes w jakikolwiek inny sposób, niż do opisywania komponentów, nie będzie już wspierane:

```javascript
var apiShape = PropTypes.shape({
body: PropTypes.object,
statusCode: PropTypes.number.isRequired
}).isRequired;

// Not supported!
// Brak wsparcia!
var error = apiShape(json, 'response');
```

If you depend on using PropTypes like this, we encourage you to use or create a fork of PropTypes (such as [these](https://github.com/aackerman/PropTypes) [two](https://github.com/developit/proptypes) packages).
Jeżeli logika twojej aplikacji jest uzależniona od użycia PropTypes w taki sposób, zachęcamy do stworzenia forka PropTypes lub użycia jednego z już istniejących (np. któregoś z [tych](https://github.com/aackerman/PropTypes) [dwóch](https://github.com/developit/proptypes)).

If you don't fix the warning, this code will crash in production with React 16.
Jeśli zignorujesz to ostrzeżenie, po aktualizacji Reacta do wersji 16 możesz spodziewać się krytycznych błędów na środowisku produkcyjnym.

### If you don't call PropTypes directly but still get the warning {#if-you-dont-call-proptypes-directly-but-still-get-the-warning}
### Ostrzeżenie pojawia się, mimo że nie wywołujesz PropTypes bezpośrednio {#if-you-dont-call-proptypes-directly-but-still-get-the-warning}

Inspect the stack trace produced by the warning. You will find the component definition responsible for the PropTypes direct call. Most likely, the issue is due to third-party PropTypes that wrap React’s PropTypes, for example:
Przyjrzyj się stosowi wywołań, który wyświetla się wraz z ostrzeżeniem. Znajdziesz w nim nazwę komponentu odpowiedzialnego za bezpośrednie wywołanie PropTypes.
Prawdopodobnie problem jest spowodowany przez zewnętrzną bibiliotekę, która opakowuje PropTypes. Przykładowo:

```js
Button.propTypes = {
Expand All @@ -55,13 +56,16 @@ Button.propTypes = {
}
```

In this case, `ThirdPartyPropTypes.deprecated` is a wrapper calling `PropTypes.bool`. This pattern by itself is fine, but triggers a false positive because React thinks you are calling PropTypes directly. The next section explains how to fix this problem for a library implementing something like `ThirdPartyPropTypes`. If it's not a library you wrote, you can file an issue against it.
Taki wzorzec sam w sobie jest w porządku, lecz powoduje on fałszywe ostrzeżenie, ponieważ React "myśli", że PropTypes wywoływane jest bezpośrednio.
W następnej sekcji przeczytasz, jak uporać się z takim ostrzeżeniem będąc autorem biblioteki, w której pojawia się implementacja czegoś podobnego do `ThirdPartyPropTypes`. Jeśli ostrzeżenie pochodzi z biblioteki, której nie jesteś autorem, możesz zgłosić błąd jej autorom.

### Fixing the false positive in third party PropTypes {#fixing-the-false-positive-in-third-party-proptypes}
### Jak poprawić fałszywe ostrzeżenie w zewnętrznych PropTypes {#fixing-the-false-positive-in-third-party-proptypes}

If you are an author of a third party PropTypes library and you let consumers wrap existing React PropTypes, they might start seeing this warning coming from your library. This happens because React doesn't see a "secret" last argument that [it passes](https://github.com/facebook/react/pull/7132) to detect manual PropTypes calls.
Jeśli jesteś autorem biblioteki operującej na PropTypes i pozwalasz użytkownikom na opakowywanie istniejących PropTypes, mogą oni natknąć się na ostrzeżenia pochodzące z twojej biblioteki.
Dzieje się tak, gdyż React nie widzi ostatniego, „ukrytego” parametru, [który jest przekazywany](https://github.com/facebook/react/pull/7132) po to, by wykryć bezpośrednie użycie PropTypes.

Here is how to fix it. We will use `deprecated` from [react-bootstrap/react-prop-types](https://github.com/react-bootstrap/react-prop-types/blob/0d1cd3a49a93e513325e3258b28a82ce7d38e690/src/deprecated.js) as an example. The current implementation only passes down the `props`, `propName`, and `componentName` arguments:
Oto, jak temu zaradzić. Jako przykładu użyjemy `deprecated` z [react-bootstrap/react-prop-types](https://github.com/react-bootstrap/react-prop-types/blob/0d1cd3a49a93e513325e3258b28a82ce7d38e690/src/deprecated.js).
Obecna implementacja przekazuje tylko `props`, `propName` i `componentName`:

```javascript
export default function deprecated(propType, explanation) {
Expand All @@ -79,11 +83,11 @@ export default function deprecated(propType, explanation) {
}
```

In order to fix the false positive, make sure you pass **all** arguments down to the wrapped PropType. This is easy to do with the ES6 `...rest` notation:
Aby pozbyć się błędnego ostrzeżenia, upewnij się, że przekazujesz **wszystkie** argumenty do opakowanego PropType. Łatwo to zrobić przy pomocy notacji ES6 `rest`:

```javascript
export default function deprecated(propType, explanation) {
return function validate(props, propName, componentName, ...rest) { // Note ...rest here
return function validate(props, propName, componentName, ...rest) { // dodajemy ...rest tutaj
if (props[propName] != null) {
const message = `"${propName}" property of "${componentName}" has been deprecated.\n${explanation}`;
if (!warned[message]) {
Expand All @@ -92,9 +96,9 @@ export default function deprecated(propType, explanation) {
}
}

return propType(props, propName, componentName, ...rest); // and here
return propType(props, propName, componentName, ...rest); // i tutaj
};
}
```

This will silence the warning.
To uciszy ostrzeżenie.
4 changes: 2 additions & 2 deletions examples/forwarding-refs/customized-display-name.js
Original file line number Diff line number Diff line change
Expand Up @@ -7,8 +7,8 @@ function logProps(Component) {
return <LogProps {...props} forwardedRef={ref} />;
}

// Give this component a more helpful display name in DevTools.
// e.g. "ForwardRef(logProps(MyComponent))"
// Nadajmy temu komponentowi nazwę, która będzie bardziej czytelna w narzędziach deweloperskich.
// np. "ForwardRef(logProps(MyComponent))"
// highlight-range{1-2}
const name = Component.displayName || Component.name;
forwardRef.displayName = `logProps(${name})`;
Expand Down
8 changes: 4 additions & 4 deletions examples/forwarding-refs/fancy-button-ref.js
Original file line number Diff line number Diff line change
Expand Up @@ -3,10 +3,10 @@ import FancyButton from './FancyButton';
// highlight-next-line
const ref = React.createRef();

// The FancyButton component we imported is the LogProps HOC.
// Even though the rendered output will be the same,
// Our ref will point to LogProps instead of the inner FancyButton component!
// This means we can't call e.g. ref.current.focus()
// Komponent FancyButton, który zaimportowaliśmy, jest tak naprawdę KWR-em LogProps.
// Mimo że wyświetlony rezultat będzie taki sam,
// nasza referencja będzie wskazywała na LogProps zamiast na komponent FancyButton!
// Oznacza to, że nie możemy wywołać np. metody ref.current.focus()
// highlight-range{4}
<FancyButton
label="Click Me"
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Suggested change
label="Click Me"
label="Kliknij tutaj"

Expand Down
Loading