diff --git a/content/docs/higher-order-components.md b/content/docs/higher-order-components.md index a7a123abe..b361cc5a0 100644 --- a/content/docs/higher-order-components.md +++ b/content/docs/higher-order-components.md @@ -4,29 +4,29 @@ title: Higher-Order Components permalink: docs/higher-order-components.html --- -A higher-order component (HOC) is an advanced technique in React for reusing component logic. HOCs are not part of the React API, per se. They are a pattern that emerges from React's compositional nature. +Ein Higher-Order-Component (HOC) ist eine moderne Technologie zur Wiederverwendung von Komponentenlogik in React. HOCs sind kein Teil der React API an sich, sondern ein Schema welches sich aus der Kompositionstechnik von React ergibt. -Concretely, **a higher-order component is a function that takes a component and returns a new component.** +Konkret ist **ein Higher-Order Component eine Funktion, die eine Komponente übernimmt und eine neue Komponente zurückgibt.** ```js const EnhancedComponent = higherOrderComponent(WrappedComponent); ``` -Whereas a component transforms props into UI, a higher-order component transforms a component into another component. +Während eine Komponente alle Props in UI umwandelt, wandelt die Higher-Order-Komponente eine Komponente in eine andere Komponente um. -HOCs are common in third-party React libraries, such as Redux's [`connect`](https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md#connect) and Relay's [`createFragmentContainer`](http://facebook.github.io/relay/docs/en/fragment-container.html). +HOCs finden sich häufig in React-Bibliotheken von Drittanbietern, als Beispiele dafür gelten [`connect`](https://github.com/reduxjs/react-redux/blob/master/docs/api/connect.md#connect) von Redux und [`createFragmentContainer`](http://facebook.github.io/relay/docs/en/fragment-container.html) von Relay. -In this document, we'll discuss why higher-order components are useful, and how to write your own. +In diesem Dokument, werden wir erörtern, warum Higher-Order-Komponenten nützlich sind und wie du deine eigene schreiben kannst. -## Use HOCs For Cross-Cutting Concerns {#use-hocs-for-cross-cutting-concerns} +## Nutze HOCs für übergreifende Belangen {#use-hocs-for-cross-cutting-concerns} -> **Note** +> **Hinweis** > -> We previously recommended mixins as a way to handle cross-cutting concerns. We've since realized that mixins create more trouble than they are worth. [Read more](/blog/2016/07/13/mixins-considered-harmful.html) about why we've moved away from mixins and how you can transition your existing components. +> Früher haben wir Mixins für die Handhabung von übergreifenden Belangen empfohlen. Seither hat sich allerdings herausgestellt, dass Mixins mehr Probleme als Nutzen bereiten. [Lese darüber](/blog/2016/07/13/mixins-considered-harmful.html) warum wir uns von Mixins abgewandt haben und wie du deine existierenden Komponenten umwandeln kannst. -Components are the primary unit of code reuse in React. However, you'll find that some patterns aren't a straightforward fit for traditional components. +Komponenten sind die primäre Einheit der Quellcode-Wiederverwendbarkeit in React. Nichtsdestotrotz, wirst du feststellen, dass manche Patterns nicht immer für eine traditionelle Komponente geeignet sind. -For example, say you have a `CommentList` component that subscribes to an external data source to render a list of comments: +Als Beispiel nehmen wir eine `CommentList` Komponente, die eine externe Datenequelle nutzt, um eine Liste mit Kommentaren zu rendern: ```js class CommentList extends React.Component { @@ -34,23 +34,23 @@ class CommentList extends React.Component { super(props); this.handleChange = this.handleChange.bind(this); this.state = { - // "DataSource" is some global data source + // "DataSource" ist irgendeine globale Datenquelle comments: DataSource.getComments() }; } componentDidMount() { - // Subscribe to changes + // "Höre" falls Änderungen auftreten sollten DataSource.addChangeListener(this.handleChange); } componentWillUnmount() { - // Clean up listener + // Aufräumen DataSource.removeChangeListener(this.handleChange); } handleChange() { - // Update component state whenever the data source changes + // Update den Zustand der Komponente, jedes mal wenn die Datenquelle eine Änderung bekanntgibt this.setState({ comments: DataSource.getComments() }); @@ -68,7 +68,7 @@ class CommentList extends React.Component { } ``` -Later, you write a component for subscribing to a single blog post, which follows a similar pattern: +Später, erstellst du eine Komponente die auf Änderungen in einem Blog-Eintrag "hört" und ein ähnliches Pattern einsetzt: ```js class BlogPost extends React.Component { @@ -100,15 +100,15 @@ class BlogPost extends React.Component { } ``` -`CommentList` and `BlogPost` aren't identical — they call different methods on `DataSource`, and they render different output. But much of their implementation is the same: +`CommentList` und `BlogPost` sind nicht identisch - sie rufen unterschiedliche Methoden von `DataSource` auf und sie rendern unterschiedlichen Output. Jedoch ist die Mehrheit der Implementierung gleich: -- On mount, add a change listener to `DataSource`. -- Inside the listener, call `setState` whenever the data source changes. -- On unmount, remove the change listener. +- Wenn die Komponente gemountet ist, füge einen Listener für Änderungen in `DataSource` hinzu. +- Innerhalb des Listeners, rufe `setState` auf, sobald sich die Datenquelle ändert. +- Wenn die Komponente unmountet wird, entferne den Listener. -You can imagine that in a large app, this same pattern of subscribing to `DataSource` and calling `setState` will occur over and over again. We want an abstraction that allows us to define this logic in a single place and share it across many components. This is where higher-order components excel. +Du kannst dir nun vorstellen, dass in einer großen Applikation, dieses Pattern sehr oft vorkommen wird. Wir wollen eine Abstraktion, die uns erlaubt diese Logik an einem Platz zu definieren und diese dann Komponentenübergreifend zu nutzen. Dies ist der Fall, wo sich die Higher-Order Komponenten auszeichnen. -We can write a function that creates components, like `CommentList` and `BlogPost`, that subscribe to `DataSource`. The function will accept as one of its arguments a child component that receives the subscribed data as a prop. Let's call the function `withSubscription`: +Wir können eine Funktion schreiben, die Komponenten erstellt, sowie `CommentList` und `BlogPost`, die `DataSource` als Datenquelle nutzt. Die Funktion akzeptiert als einer der Argumente eine Kind-Komponente, die Daten aus der Datenquelle als Eigenschaft erhält. Lass uns die Funktion `withSubscription` nennen: ```js const CommentListWithSubscription = withSubscription( @@ -122,14 +122,14 @@ const BlogPostWithSubscription = withSubscription( ); ``` -The first parameter is the wrapped component. The second parameter retrieves the data we're interested in, given a `DataSource` and the current props. +Der erste Parameter ist die umschlossene Komponente. Der zweite Parameter erhält die Daten, an denen wir interessiert sind, dies wird durch `DataSource` und aktuelle Props sichergestellt. -When `CommentListWithSubscription` and `BlogPostWithSubscription` are rendered, `CommentList` and `BlogPost` will be passed a `data` prop with the most current data retrieved from `DataSource`: +Wenn `CommentListWithSubscription` und `BlogPostWithSubscription` gerendert werden, wird eine `data` Eigenschaft an `CommentList` und `BlogPost` übermittelt, diese enthält die aktuellsten Daten, die von `DataSource` erhalten wurden. ```js -// This function takes a component... +// Diese Funktion nimmt eine Komponente... function withSubscription(WrappedComponent, selectData) { - // ...and returns another component... + // ...und gibt eine andere Komponente zurück... return class extends React.Component { constructor(props) { super(props); @@ -140,7 +140,7 @@ function withSubscription(WrappedComponent, selectData) { } componentDidMount() { - // ... that takes care of the subscription... + // ... Das stellt sicher, dass Datenänderungen bearbeitet werden... DataSource.addChangeListener(this.handleChange); } @@ -155,83 +155,83 @@ function withSubscription(WrappedComponent, selectData) { } render() { - // ... and renders the wrapped component with the fresh data! - // Notice that we pass through any additional props + // ... rendern der umschlossenen Komponente mit aktuellsten Daten! + // Beachte, dass wir jegliche zusätzliche Props weiterleiten return ; } }; } ``` -Note that a HOC doesn't modify the input component, nor does it use inheritance to copy its behavior. Rather, a HOC *composes* the original component by *wrapping* it in a container component. A HOC is a pure function with zero side-effects. +Beachte, dass eine HOC die übergebene Komponente nicht modifiziert, des Weiteren findet auch keine Vererbung statt um dessen Verhalten zu kopieren. Stattdessen *setzt* eine HOC die ursprüngliche Komponente zusammen, in dem sie diese mit einer Container-Komponente *umschließt*. Eine HOC ist eine reine Funktion ohne Nebenwirkungen. -And that's it! The wrapped component receives all the props of the container, along with a new prop, `data`, which it uses to render its output. The HOC isn't concerned with how or why the data is used, and the wrapped component isn't concerned with where the data came from. +Das ist alles! Die umschlossene Komponente erhält alle Eigenschaften des Containers, zusammen mit einer neuen Eigenschaft, `data`, die für das Rendern des Outputs verwendet wird. Die HOC ist nicht dafür zuständig, das Wie oder Warum bei der Datenverwendung zu beantworten, ebenso wie die umschlossene Komponente nicht über die Herkunft der Daten zuständig ist. -Because `withSubscription` is a normal function, you can add as many or as few arguments as you like. For example, you may want to make the name of the `data` prop configurable, to further isolate the HOC from the wrapped component. Or you could accept an argument that configures `shouldComponentUpdate`, or one that configures the data source. These are all possible because the HOC has full control over how the component is defined. +Da `withSubscription` eine normale Funktion ist, kannst du beliebig viele, oder beliebig wenige Argumente übergeben. Zum Beispiel, du möchtest den Namen der `data` Eigenschaft konfigurierbar machen, um die HOC mehr von der umschlossenen Komponente zu isolieren. Oder du könntest ein Argument hinzufügen, welches `shouldComponentUpdate` konfiguriert, oder eines welches die Datenquelle konfiguriert. All das ist möglich, weil die HOC die volle Kontroll darübere hat, wie eine Komponente definiert wird. -Like components, the contract between `withSubscription` and the wrapped component is entirely props-based. This makes it easy to swap one HOC for a different one, as long as they provide the same props to the wrapped component. This may be useful if you change data-fetching libraries, for example. +Wie bei den Komponenten, ist die Abhängigkeit zwischen `withSubscription` und der umschlossenen Komponente rein Eigenschaftenbasiert. Dies ermöglicht einen einfachen Austausch einer bestehenden HOC durch eine andere, so lange diese die gleichen Eigenschaften an die umschlossene Komponente bereitstellen. Dies kann nützlich sein, wenn du zum Beispiel die Bibliothek für das Abrufen von Daten änderst. -## Don't Mutate the Original Component. Use Composition. {#dont-mutate-the-original-component-use-composition} +## Verändere nicht die usprüngliche Komponente. Verwende Komposition. {#dont-mutate-the-original-component-use-composition} -Resist the temptation to modify a component's prototype (or otherwise mutate it) inside a HOC. +Widerstehe der Versuchung den Prototype einer Komponente innerhalb einer HOC zu modifizieren (oder anderweitig zu verändern). ```js function logProps(InputComponent) { InputComponent.prototype.componentWillReceiveProps = function(nextProps) { - console.log('Current props: ', this.props); - console.log('Next props: ', nextProps); + console.log('Aktuelle Eigenschaften: ', this.props); + console.log('Neue Eigenschaften: ', nextProps); }; - // The fact that we're returning the original input is a hint that it has - // been mutated. + // Die Tatsache, dass wir die originale Eingang-Komponente zurückgeben, ist ein Hinweis + // dass diese verändert wurde. return InputComponent; } -// EnhancedComponent will log whenever props are received +// EnhancedComponent wird bei jedem Erhalt der Eigenschaften in die Konsole loggen const EnhancedComponent = logProps(InputComponent); ``` -There are a few problems with this. One is that the input component cannot be reused separately from the enhanced component. More crucially, if you apply another HOC to `EnhancedComponent` that *also* mutates `componentWillReceiveProps`, the first HOC's functionality will be overridden! This HOC also won't work with function components, which do not have lifecycle methods. +Es gibt einige Probleme hier. Zum einen kann die Eingang-Komponente nicht abseits der erweiterten Komponente wiederverwendet werden. Des Weiteren, wenn du eine andere HOC auf die `EnhancedComponent` anwendest die *ebenso* `componentWillReceiveProps` verändert, wird die erste Funktionalität der HOC überschrieben! Diese HOC kann auch nicht auf funktionale Komponenten angewandt werden, da diese keine Lifecycle-Methoden besitzen. -Mutating HOCs are a leaky abstraction—the consumer must know how they are implemented in order to avoid conflicts with other HOCs. +Verändernde HOCs sind eine schlecht isolierte Abstraktion - der Anwender muss über die Implementierungsdetails bescheidwissen, um Konflikte mit anderen HOCs zu vermeiden. -Instead of mutation, HOCs should use composition, by wrapping the input component in a container component: +Statt der Veränderung, sollte der Grundsatz der Komposition bei HOCs angewandt werden, in dem die Eingang-Komponente mit einer Container-Komponente umgeben wird: ```js function logProps(WrappedComponent) { return class extends React.Component { componentWillReceiveProps(nextProps) { - console.log('Current props: ', this.props); - console.log('Next props: ', nextProps); + console.log('Aktuelle Eigenschaften: ', this.props); + console.log('Neue Eigenschaften: ', nextProps); } render() { - // Wraps the input component in a container, without mutating it. Good! + // Umschließt die Eingang-Kompnente in ein Container, ohne diese zu verändern. Gut so! return ; } } } ``` -This HOC has the same functionality as the mutating version while avoiding the potential for clashes. It works equally well with class and function components. And because it's a pure function, it's composable with other HOCs, or even with itself. +Diese HOC hat die gleiche Funktionalität wie die verändernde Version, jedoch ohne der potenziellen Gefahr für Konflikte. Es funktioniert gleich gut mit klassenbasierten und funktionalen Komponenten. Und da es eine reine Funktion ist, kann sie mit anderen HOCs, oder sogar mit sich selbst zusammengesetzt werden. -You may have noticed similarities between HOCs and a pattern called **container components**. Container components are part of a strategy of separating responsibility between high-level and low-level concerns. Containers manage things like subscriptions and state, and pass props to components that handle things like rendering UI. HOCs use containers as part of their implementation. You can think of HOCs as parameterized container component definitions. +Vielleicht sind dir die Gemeinsamkeiten zwischen HOCs und dem **Container Komponenten** Pattern aufgefallen. Container Komponenten sind ein Teil der Strategie, in der eine Trennung der Zuständigkeiten zwischen übergreifenden und untergeordneten Anliegen vorgenommen wird. Container verwalten Dinge wie Abonnements und Zustand, des Weiteren geben die Eigenschaften an Komponenten weiter, die für das Rendering der UI zuständig sind. HOCs verwenden Container als Teil der Implementierung. Du kannst HOCs mit einer parametrisierten Container-Komponenten Definition vergleichen. -## Convention: Pass Unrelated Props Through to the Wrapped Component {#convention-pass-unrelated-props-through-to-the-wrapped-component} +## Konvention: Übergeben von unzusammenhängenden Eigenschaften durch die umgschlossene Komponente {#convention-pass-unrelated-props-through-to-the-wrapped-component} -HOCs add features to a component. They shouldn't drastically alter its contract. It's expected that the component returned from a HOC has a similar interface to the wrapped component. +HOCs fügt Features zu einer Komponente hinzu. Diese sollten keine drastische Veränderungen an dessen Abhängigkeit vornehmen. Es wird erwartet, dass die von der HOC zurückgegebene Komponente ein ähnliches Interface besitzt, wie die umschlossene Komponente. -HOCs should pass through props that are unrelated to its specific concern. Most HOCs contain a render method that looks something like this: +HOCs sollten Eigenschaften durchleiten, die keine Bedeutung für dessen Zweck besitzen. Die meisten HOCs besitzen eine Render-Methode die folgend aussieht: ```js render() { - // Filter out extra props that are specific to this HOC and shouldn't be - // passed through + // Filtere die extra Eigenschaften raus, die spezifisch für diese HOC sind + // und nicht weitergeleitet werden sollen const { extraProp, ...passThroughProps } = this.props; - // Inject props into the wrapped component. These are usually state values or - // instance methods. + // Injiziere Eigeschaften in die umschlossene Komponente. In den meisten Fällen + // sind es Zustandswerte oder Instanzenmethoden const injectedProp = someStateOrInstanceMethod; - // Pass props to wrapped component + // Übergebe die Eigenschaften an die umschlossene Komponente return ( Component`. Functions whose output type is the same as its input type are really easy to compose together. +Diese Form kann verwirrend oder unnötig erscheinen, es hat jedoch eine nützliche Eigenschaft. HOCs mit einzigem Argument, wie die, die von der `connect` Funktion zurückgegeben werden besitzen die Signatur `Component => Component`. Funktionen dessen Ausgabetyp dem Eingabetyp gleicht, können sehr einfach zusammengesetzt werden. ```js -// Instead of doing this... +// Anstatt folgendes zu machen... const EnhancedComponent = withRouter(connect(commentSelector)(WrappedComponent)) -// ... you can use a function composition utility -// compose(f, g, h) is the same as (...args) => f(g(h(...args))) +// ... kannst du ein Utility zur Zusammensetzung der Funktion nutzen +// compose(f, g, h) ist gleichzusetzen mit (...args) => f(g(h(...args))) const enhance = compose( - // These are both single-argument HOCs + // Dies sind HOCs mit einem einzelnen Argument withRouter, connect(commentSelector) ) const EnhancedComponent = enhance(WrappedComponent) ``` -(This same property also allows `connect` and other enhancer-style HOCs to be used as decorators, an experimental JavaScript proposal.) +(Diese Eigenschaft ermöglicht die Verwendung von `connect` und anderen Enhancer-basierten HOCs als Dekoratoren, welche ein experimentelles JavaScript Entwurf darstellen.) -The `compose` utility function is provided by many third-party libraries including lodash (as [`lodash.flowRight`](https://lodash.com/docs/#flowRight)), [Redux](https://redux.js.org/api/compose), and [Ramda](https://ramdajs.com/docs/#compose). +Die `componse` Utility-Funktion wird von vielen Drittanbieter-Bibliotheken wie lodash (als [`lodash.flowRight`](https://lodash.com/docs/#flowRight)), [Redux](https://redux.js.org/api/compose) und [Ramda](https://ramdajs.com/docs/#compose) angeboten. -## Convention: Wrap the Display Name for Easy Debugging {#convention-wrap-the-display-name-for-easy-debugging} +## Konvention: Umschließe den Anzeigenamen für ein einfaches Debugging {#convention-wrap-the-display-name-for-easy-debugging} -The container components created by HOCs show up in the [React Developer Tools](https://github.com/facebook/react-devtools) like any other component. To ease debugging, choose a display name that communicates that it's the result of a HOC. +Die Container Komponenten di von HOCs erstellt werden, erscheinen in den [React Developer Tools](https://github.com/facebook/react-devtools) wie jede andere Komponente. Um das Debugging zu erleichtern, wähle einen Anzeigenamen aus, der mitteilt, dass es ein Ergebnis einer HOC ist. -The most common technique is to wrap the display name of the wrapped component. So if your higher-order component is named `withSubscription`, and the wrapped component's display name is `CommentList`, use the display name `WithSubscription(CommentList)`: +Das Umschließen des Anzeigenamens der umzuschließenden Komponente ist ein gebräuchlicher Ansatz. Wenn deine Higher-Order Komponente `withSubscription` heißt und der Name der umschlossenen Komponente ist `CommentList`, nutze `WithSubscription(CommentList)` als Anzeigenamen: ```js function withSubscription(WrappedComponent) { @@ -314,60 +314,60 @@ function getDisplayName(WrappedComponent) { ``` -## Caveats {#caveats} +## Vorbehalte {#caveats} -Higher-order components come with a few caveats that aren't immediately obvious if you're new to React. +Higher-Order Komponenten kommen mit einigen Vorbehalten, die nicht sofort ersichtlich sind wenn du dich erst mit React vertraut machst. -### Don't Use HOCs Inside the render Method {#dont-use-hocs-inside-the-render-method} +### Vermeide die Nutzung von HOCs innerhalb der Render-Methode {#dont-use-hocs-inside-the-render-method} -React's diffing algorithm (called reconciliation) uses component identity to determine whether it should update the existing subtree or throw it away and mount a new one. If the component returned from `render` is identical (`===`) to the component from the previous render, React recursively updates the subtree by diffing it with the new one. If they're not equal, the previous subtree is unmounted completely. +Der Differenzierungsalgorithmus von React (auch Abgleich genannt) nutzt die Identität der Komponente, um zu bestimmen, ob der existierende Teilbaum aktualisiert, oder weggeworfen werden soll und ob das Mounten eines neuen Teilbaums notwendig ist. Wenn die von der `render` Methode zurückgegebene Komponente identisch (`===`) zu der vorher zurückgegebenen Komponente ist, wird der Teilbaum rekursiv von React upgedated, in dem eine Differenzierung des alten Teilbaums mit dem neuen Teilbaum stattfindet. Wenn die beiden ungleich sind, wird der vorherige Teilbaum zur Gänze unmounted. -Normally, you shouldn't need to think about this. But it matters for HOCs because it means you can't apply a HOC to a component within the render method of a component: +Normalerweise, solltest du keine Gedanken darüber verlieren. Jedoch spielt dies eine wesentliche Rolle für HOCs, da dies bedeutet, dass du eine HOC auf eine Komponente innerhalb der Render-Methode einer Komponente nicht anwenden kannst: ```js render() { - // A new version of EnhancedComponent is created on every render + // Eine neue Version von EnhancedComponent wird bei jedem Render-Vorgang erstellt // EnhancedComponent1 !== EnhancedComponent2 const EnhancedComponent = enhance(MyComponent); - // That causes the entire subtree to unmount/remount each time! + // Dies bewirkt dass jedesmal ein Unmounten/Remounten des ganzen Teilbaus stattfindet return ; } ``` -The problem here isn't just about performance — remounting a component causes the state of that component and all of its children to be lost. +Das Problem hier ist nicht nur die Performance - das Remounten einer Komponente führt zum Verlust des Zustandes sowohl bei der Komponente selbst, als auch bei all ihren Kind-Komponenten. -Instead, apply HOCs outside the component definition so that the resulting component is created only once. Then, its identity will be consistent across renders. This is usually what you want, anyway. +Stattdessen, solltest du die HOCs außerhalb der Definition einer Komponente anwenden, um sicherzustellen, dass die Komponente nur ein einziges Mal erstellt wird. Nur dann ist dessen Identität konsistent und übergreifend zwischen den einzelnen Rendervorgängen sichergestellt. Normalerweise ist dies sowieso das, was du willst. -In those rare cases where you need to apply a HOC dynamically, you can also do it inside a component's lifecycle methods or its constructor. +In den seltenen Fällen wo du eine HOC dynamisch anwenden möchtest, kannst du dies innerhalb der Lifecycle-Methoden einer Komponente oder im Konstruktor machen. -### Static Methods Must Be Copied Over {#static-methods-must-be-copied-over} +### Statische Methoden müssen kopiert werden {#static-methods-must-be-copied-over} -Sometimes it's useful to define a static method on a React component. For example, Relay containers expose a static method `getFragment` to facilitate the composition of GraphQL fragments. +Manchmal ist es nützlich eine statische Methode in einer React Komponente zu definieren. Zum Beispiel, Relay Kontainer stellen eine statische Methode `getFragment` zur Verfügung, um die Zusammensetzung der GraphQL Fragmente zu erleichtern. -When you apply a HOC to a component, though, the original component is wrapped with a container component. That means the new component does not have any of the static methods of the original component. +Wenn du jedoch eine HOC auf eine Komponente anwendest, wird die ursprüngliche Komponente mit einer Container-Komponente umgeben. Dies bedeutet, dass die neue Komponente keine der statischen Methoden der usprünglichen Komponente besitzt. ```js -// Define a static method +// Definiere eine statische Methode WrappedComponent.staticMethod = function() {/*...*/} -// Now apply a HOC +// Nun wende eine HOC an const EnhancedComponent = enhance(WrappedComponent); -// The enhanced component has no static method +// Die erweiterte Komponente hat keine statische Methode typeof EnhancedComponent.staticMethod === 'undefined' // true ``` -To solve this, you could copy the methods onto the container before returning it: +Um dies zu lösen, kannst du die Methoden in den Container kopieren, bevor du diesen zurückgibst ```js function enhance(WrappedComponent) { class Enhance extends React.Component {/*...*/} - // Must know exactly which method(s) to copy :( + // Du musst genau wissen, welche Methode(n) du kopieren möchtest :( Enhance.staticMethod = WrappedComponent.staticMethod; return Enhance; } ``` -However, this requires you to know exactly which methods need to be copied. You can use [hoist-non-react-statics](https://github.com/mridgway/hoist-non-react-statics) to automatically copy all non-React static methods: +Dennoch, dies erfordert dass du genau weißt welche Methoden kopiert werden müssen. Du kannst [hoist-non-react-statics](https://github.com/mridgway/hoist-non-react-statics) nutzen, um automatisch alle statische Methoden die nicht zu React gehören zu kopieren: ```js import hoistNonReactStatic from 'hoist-non-react-statics'; @@ -378,22 +378,22 @@ function enhance(WrappedComponent) { } ``` -Another possible solution is to export the static method separately from the component itself. +Eine andere mögliche Lösung wäre das Exportieren der statischen Methode unabhängig von der Komponente. ```js -// Instead of... +// Statt... MyComponent.someFunction = someFunction; export default MyComponent; -// ...export the method separately... +// ...exportiere die Methode separat... export { someFunction }; -// ...and in the consuming module, import both +// ...importiere beide in die gewünschte Komponente import MyComponent, { someFunction } from './MyComponent.js'; ``` -### Refs Aren't Passed Through {#refs-arent-passed-through} +### Refs werden nicht weitergeleitet {#refs-arent-passed-through} -While the convention for higher-order components is to pass through all props to the wrapped component, this does not work for refs. That's because `ref` is not really a prop — like `key`, it's handled specially by React. If you add a ref to an element whose component is the result of a HOC, the ref refers to an instance of the outermost container component, not the wrapped component. +Obwohl die Konvention für Higher-Order Komponente besagt, dass alle Eigenschaften an die umschlossene Komponente weiteregeleitet werden sollen, funktioniert dieser Ansatz für Refs nicht. Das kommt daher, weil `ref` nicht wirklich eine Eigenschaft ist - wie `key`, wird es besonders von React behandelt. Wenn du eine Ref zu einem Element hinzufügen möchtest, welches das Ergebnis einer HOC ist, wird das Ref auf die Instanz der äußersten Container-Komponente zeigen und nicht auf die umschlossene Komponente. -The solution for this problem is to use the `React.forwardRef` API (introduced with React 16.3). [Learn more about it in the forwarding refs section](/docs/forwarding-refs.html). +Die Lösung für dieses Problem ist die Verwendung von `React.forwardRef` API (eingeführt mit React 16.3). [Learn more about it in the forwarding refs section](/docs/forwarding-refs.html).