Browse Source
Merge pull request #738 from koba04/forward-ref-examples
React.forwardRef accepts a render function, not Functional Component
main
Brian Vaughn
7 years ago
committed by
GitHub
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
1 changed files with
16 additions and
15 deletions
-
examples/16-3-release-blog-post/forward-ref-example.js
|
@ -1,27 +1,28 @@ |
|
|
function withTheme(Component) { |
|
|
function withTheme(Component) { |
|
|
// Note the second param "ref" provided by React.forwardRef.
|
|
|
// highlight-next-line
|
|
|
// We can attach this to Component directly.
|
|
|
function ThemedComponent({forwardedRef, ...rest}) { |
|
|
// highlight-range{1,5}
|
|
|
|
|
|
function ThemedComponent(props, ref) { |
|
|
|
|
|
return ( |
|
|
return ( |
|
|
<ThemeContext.Consumer> |
|
|
<ThemeContext.Consumer> |
|
|
{theme => ( |
|
|
{theme => ( |
|
|
<Component {...props} ref={ref} theme={theme} /> |
|
|
// Assign the custom prop "forwardedRef" as a ref
|
|
|
|
|
|
// highlight-next-line
|
|
|
|
|
|
<Component |
|
|
|
|
|
{...rest} |
|
|
|
|
|
ref={forwardedRef} |
|
|
|
|
|
theme={theme} |
|
|
|
|
|
/> |
|
|
)} |
|
|
)} |
|
|
</ThemeContext.Consumer> |
|
|
</ThemeContext.Consumer> |
|
|
); |
|
|
); |
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
// These next lines are not necessary,
|
|
|
// Note the second param "ref" provided by React.forwardRef.
|
|
|
// But they do give the component a better display name in DevTools,
|
|
|
// We can pass it along to ThemedComponent as a regular prop, e.g. "forwardedRef"
|
|
|
// e.g. "ForwardRef(withTheme(MyComponent))"
|
|
|
// And it can then be attached to the Component.
|
|
|
// highlight-range{1-2}
|
|
|
// highlight-range{1-3}
|
|
|
const name = Component.displayName || Component.name; |
|
|
return React.forwardRef((props, ref) => ( |
|
|
ThemedComponent.displayName = `withTheme(${name})`; |
|
|
<ThemedComponent {...props} forwardedRef={ref} /> |
|
|
|
|
|
)); |
|
|
// Tell React to pass the "ref" to ThemedComponent.
|
|
|
|
|
|
// highlight-next-line
|
|
|
|
|
|
return React.forwardRef(ThemedComponent); |
|
|
|
|
|
} |
|
|
} |
|
|
|
|
|
|
|
|
// highlight-next-line
|
|
|
// highlight-next-line
|
|
|