Brian Vaughn
7 years ago
5 changed files with 94 additions and 3 deletions
@ -0,0 +1,32 @@ |
|||
class FancyButton extends React.Component { |
|||
buttonRef = React.createRef(); |
|||
|
|||
focus() { |
|||
this.buttonRef.current.focus(); |
|||
} |
|||
|
|||
render() { |
|||
// highlight-next-line
|
|||
const {label, theme, ...rest} = this.props; |
|||
// highlight-range{4}
|
|||
return ( |
|||
<button |
|||
{...rest} |
|||
className={`${theme}-button`} |
|||
ref={this.buttonRef}> |
|||
{label} |
|||
</button> |
|||
); |
|||
} |
|||
} |
|||
|
|||
// highlight-next-line
|
|||
const FancyThemedButton = withTheme(FancyButton); |
|||
|
|||
// We can render FancyThemedButton as if it were a FancyButton
|
|||
// It will automatically receive the current "theme",
|
|||
// And the HOC will pass through our other props.
|
|||
<FancyThemedButton |
|||
label="Click me!" |
|||
onClick={handleClick} |
|||
/>; |
@ -0,0 +1,34 @@ |
|||
function withTheme(Component) { |
|||
// highlight-next-line
|
|||
function ThemedComponent({forwardedRef, ...rest}) { |
|||
// highlight-range{6}
|
|||
return ( |
|||
<ThemeContext.Consumer> |
|||
{theme => ( |
|||
<Component |
|||
{...rest} |
|||
ref={forwardedRef} |
|||
theme={theme} |
|||
/> |
|||
)} |
|||
</ThemeContext.Consumer> |
|||
); |
|||
} |
|||
|
|||
// Intercept the "ref" and pass it as a custom prop.
|
|||
// highlight-range{1-3}
|
|||
return React.forwardRef((props, ref) => ( |
|||
<ThemedComponent {...props} forwardedRef={ref} /> |
|||
)); |
|||
} |
|||
|
|||
// highlight-next-line
|
|||
const fancyButtonRef = React.createRef(); |
|||
|
|||
// fancyButtonRef will now point to FancyButton
|
|||
// highlight-range{4}
|
|||
<FancyThemedButton |
|||
label="Click me!" |
|||
onClick={handleClick} |
|||
ref={fancyButtonRef} |
|||
/>; |
@ -0,0 +1,10 @@ |
|||
function withTheme(Component) { |
|||
return function ThemedComponent(props) { |
|||
// highlight-range{2-4}
|
|||
return ( |
|||
<ThemeContext.Consumer> |
|||
{theme => <Component {...props} theme={theme} />} |
|||
</ThemeContext.Consumer> |
|||
); |
|||
}; |
|||
} |
Loading…
Reference in new issue