Skip to content

Translation: "Forwarding Refs" #110

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

Merged
merged 5 commits into from
Oct 25, 2019
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
65 changes: 32 additions & 33 deletions content/docs/forwarding-refs.md
Original file line number Diff line number Diff line change
@@ -1,76 +1,75 @@
---
id: forwarding-refs
title: Forwarding Refs
title: Weiterleiten von Refs
permalink: docs/forwarding-refs.html
---
Weiterleiten von Refs ist eine Technik für die automatische Übergabe einer [Ref](/docs/refs-and-the-dom.html) durch eine Komponente an eines seiner Kinder. Normalerweise besteht für die meisten Komponenten innerhalb einer Anwendung kein Bedarf dafür. Nichtsdestotrotz, kann es für gewisse Arten von Komponenten nützlich sein, vor allem wenn es sich dabei um wiederverwendbare Komponenten-Bibliotheken handelt. Die gängigsten Szenarien werden unterhalb beschrieben.

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.
## Weiterleiten von Refs zu DOM-Komponenten {#forwarding-refs-to-dom-components}

## Forwarding refs to DOM components {#forwarding-refs-to-dom-components}

Consider a `FancyButton` component that renders the native `button` DOM element:
Stelle dir eine `FancyButton` Komponente vor, welche das native `button` DOM-Element rendert:
`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.
React Komponenten verbergen ihre Implementierungsdetails, einschließlich der gerenderten Ausgabe. Andere Komponenten die `FancyButton` benutzen, werden **in den meisten Fällen keine Notwendigkeit** für den [Abruf einer Ref](/docs/refs-and-the-dom.html) zum inneren `button` DOM-Element haben. Das ist gut so, da dies eine zu starke Abhängigkeit unter den Komponenten auf die gegenseitige DOM-Struktur verhindert.

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.
Trotz der Tatsache, dass solch eine Kapselung für Komponenten in der Anwendungsebene wie `FeedStory` oder `Comment` erwünscht ist, kann dies für "Blatt-Komponenten" mit einem hohen Wiederverwendbarkeitsgrad, wie `FancyButton` oder `MyTextInput` unpraktisch sein. Diese Komponenten werden oft in der ganzen Anwendung als reguläre DOM `button` und `input` auf ähnliche Weise eingesetzt und der Zugriff auf dessen DOM-Knoten könnte für die Regelung von Fokus, Auswahl oder Animationen unvermeidlich sein.

**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.**
**Die Weiterleitung von Refs ist ein Opt-In Feature, welches manchen Komponenten die Möglichkeit bereitstellt, eine erhaltene `ref`, weiter nach unten zu einem Kind durchzulassen (in anderen Worten, "weiterzuleiten").**

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:
Im unteren Beispiel benutzt `FancyButton` `React.forwardRef`, um die übermittelte `ref` abzurufen und diese anschließend an den gerenderten DOM `button` weiterzuleiten.

`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.
In diesem Fall, können die Komponenten die `FancyButton` nutzen, das Ref zum unterliegenden `button` DOM-Knoten abrufen und dies bei bedarf nutzen—so als ob sie direkt auf den DOM `button` zugreifen würden.

Here is a step-by-step explanation of what happens in the above example:
Hier ist eine Schritt für Schritt Erklärung was im oberen Beispiel passiert:

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. Wir erstellen eine [React Ref](/docs/refs-and-the-dom.html) mit dem Aufruf von `React.createRef` und weisen es der `ref` Variable zu.
1. Wir geben unsere `ref` an `<FancyButton ref={ref}>` weiter, in dem wir diese als JSX Attribut definieren.
1. React gibt die `ref` der `(props, ref) => ...` Funktion innerhalb von `forwardRef` als zweites Argument weiter.
1. Mit der Definition als JSX Attribut, leiten wir das `ref` Argument weiter zum `<button ref={ref}>`.
1. When das Ref zugewiesen ist, zeigt `ref.current` auf den `<button>` DOM-Knoten.

>Note
> Hinweis
>
>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.
> Das zweite `ref` Argument existiert nur dann, wenn du eine Komponente mit `React.forwardRef` Aufruf definierst. Normale Funktion- oder Klassenkomponenten erhalten das `ref` Argument nicht, es ist auch nicht in den Props verfügbar.
>
>Ref forwarding is not limited to DOM components. You can forward refs to class component instances, too.
> Das Weiterleiten von Refs ist nicht nur auf DOM-Komponenten limitiert. Du kannst auch Refs zu Instanzen von Klassenkomponenten weiterleiten.

## Note for component library maintainers {#note-for-component-library-maintainers}
## Hinweis für Betreiber von Komponentenbibliotheken {#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.
**Wenn du anfängst `forwardRef` in einer Komponentenbibliothek zu nutzen, solltest du es als funktionsgefährdende Änderung behandeln und eine neue Major-Version deiner Bibliothek veröffentlichen.** Deine Bibliothek wird höchstwahrscheinlich ein wahrnehmbar anderes Verhalten aufweisen (z.B. Zuordnung von Refs, welche Typen werden exportiert), dies könnte negative Auswirkungen auf andere Anwendungen und Bibliotheken haben, die auf das alte Verhalten angewiesen sind.

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.
Bedingte Anwendung von `React.forwardRef` bei Vorhandensein, ist ebenso aus den gleichen Gründen nicht ratsam: es verändert das Verhalten deiner Bibliothek und könnte negative Auswirkungen auf die Anwendungen deiner User haben, wenn sie ein React-Upgrade durchführen.

## Forwarding refs in higher-order components {#forwarding-refs-in-higher-order-components}
## Weiterleiten von Refs in Higher-Order-Komponenten {#forwarding-refs-in-higher-order-components}

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:
Diese Technik kann besonders in Verbindung mit [Higher-Order-Komponenten](/docs/higher-order-components.html) (auch bekannt als HOC) nützlich sein. Beginnen wir mit einer Beispiel-HOC, welche die Eigenschaften einer Komponente in die Konsole loggt:
`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:
Die "logProps" HOC gibt alle `props` an die Komponente durch, die von ihr umschlossen wird, aus diesem Grund wird die gerenderte Ausgabe gleich sein. Wir können zum Beispiel diese HOC nutzen, um alle Eigenschaften zu loggen, die an unsere "fancy button" Komponente weitergegeben werden:
`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.
Folgendes muss im oberen Beispiel beachtet werden: es werden keine Refs weitergegeben. Das ist der Tatsache zu entnehmen, dass `ref` keine Eigenschaft ist. Ähnlich dem `key`, wird es anders von React behandelt. Wenn du eine Ref zu einer HOC hinzufügst, wird diese die äußerste Container-Komponente und nicht die umschlossene Komponente referenzieren.

This means that refs intended for our `FancyButton` component will actually be attached to the `LogProps` component:
Dies bedeutet, dass Refs die für unsere `FancyButton` Komponente bestimmt waren, eigentlich der `LogProps` Komponente zugewiesen sein werden:
`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:
Glücklicherweise, können wir Refs explizit an die innere `FancyButton` Komponente weiterleiten, in dem wir die `React.forwardRef` API benutzen. `React.forwardRef` akzeptiert eine render-Funktion, die `props` und `ref` Eigenschaften enthält und einen React-Knoten zurückgibt. Beispiel:
`embed:forwarding-refs/log-props-after.js`

## Displaying a custom name in DevTools {#displaying-a-custom-name-in-devtools}
## Anzeigen von benutzerdefinierten Namen in DevTools {#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` akzeptiert eine render-Funktion. React DevTools nutzt diese Funktion um zu bestimmen, was für die Ref-weiterleitende Komponente angezeigt werden soll.

For example, the following component will appear as "*ForwardRef*" in the DevTools:
Zum Beispiel, folgende Komponente wird als "*ForwardRef*" in DevTools aufscheinen.

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

If you name the render function, DevTools will also include its name (e.g. "*ForwardRef(myFunction)*"):
Wenn du die render-Funktion benennst, wird dieser auch innerhalb von DevTools inkludiert (z.B. "*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:
Du kannst sogar die Eigenschaft `displayName` setzen, um die umschlossene Komponente zu inkludieren.

`embed:forwarding-refs/customized-display-name.js`
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))"
// Weise dieser Komponente einen aussagekräftigen Namen in DevTools zu.
// z.B. "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()
// Die FancyButton Komponente die wir importieren ist die LogProps HOK.
// Auch wenn die gerenderte Ausgabe gleich bleibt,
// wird unsere Ref auf `LogProps` statt auf die innere FancyButton Komponente verweisen!
// Dies bedeutet, dass wir z.B. kein ref.current.focus() aufrufen können.
// highlight-range{4}
<FancyButton
label="Click Me"
Expand Down
2 changes: 1 addition & 1 deletion examples/forwarding-refs/fancy-button-simple-ref.js
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,6 @@ const FancyButton = React.forwardRef((props, ref) => (
</button>
));

// You can now get a ref directly to the DOM button:
// Du kannst jetzt ein Ref direkt zum DOM button bekommen:
const ref = React.createRef();
<FancyButton ref={ref}>Click me!</FancyButton>;
4 changes: 2 additions & 2 deletions examples/forwarding-refs/fancy-button.js
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@ class FancyButton extends React.Component {
// ...
}

// Rather than exporting FancyButton, we export LogProps.
// It will render a FancyButton though.
// Anstatt die FancyButton Komponente zu exportieren, exportieren wir LogProps.
// Es wird trotzdem der FancyButton gerendert.
// highlight-next-line
export default logProps(FancyButton);
8 changes: 4 additions & 4 deletions examples/forwarding-refs/log-props-after.js
Original file line number Diff line number Diff line change
Expand Up @@ -9,15 +9,15 @@ function logProps(Component) {
// highlight-next-line
const {forwardedRef, ...rest} = this.props;

// Assign the custom prop "forwardedRef" as a ref
// Weise die benutzerdefinierte Eigenschaft "forwardRef" als Ref zu
// highlight-next-line
return <Component ref={forwardedRef} {...rest} />;
}
}

// Note the second param "ref" provided by React.forwardRef.
// We can pass it along to LogProps as a regular prop, e.g. "forwardedRef"
// And it can then be attached to the Component.
// Beachte das zweite Attribut "ref", welches von React.forwardRef bereitgestellt wird.
// Wir können es an LogProps wie eine reguläre Eigenschaft weiterleiten, z.B. "forwardRef"
// Und es kann einer Komponente zugewiesen werden.
// highlight-range{1-3}
return React.forwardRef((props, ref) => {
return <LogProps {...props} forwardedRef={ref} />;
Expand Down
4 changes: 2 additions & 2 deletions examples/forwarding-refs/log-props-before.js
Original file line number Diff line number Diff line change
Expand Up @@ -2,8 +2,8 @@
function logProps(WrappedComponent) {
class LogProps extends React.Component {
componentDidUpdate(prevProps) {
console.log('old props:', prevProps);
console.log('new props:', this.props);
console.log('Alte Eigenschaften:', prevProps);
console.log('Neue Eigenschaften:', this.props);
}

render() {
Expand Down