Add ref forwarding, lifecycle examples

This commit is contained in:
Alex Krolick
2018-03-22 21:15:40 -07:00
parent fec6d6c141
commit 7b5764fed5
3 changed files with 43 additions and 0 deletions

View File

@@ -16,6 +16,9 @@ In a typical React application, data is passed top-down (parent to child) via pr
- [Examples](#examples)
- [Static Context](#static-context)
- [Dynamic Context](#dynamic-context)
- [Consuming Multiple Contexts](#consuming-multiple-contexts)
- [Accessing Context in Lifecycle Methods](#accessing-context-in-lifecycle-methods)
- [Forwarding Refs to Context Consumers](#forwarding-refs-to-context-consumers)
- [Legacy API](#legacy-api)
@@ -91,6 +94,15 @@ A more complex example with dynamic values for the theme:
## Consuming Multiple Contexts
`embed:context/multiple-contexts.js`
## Accessing Context in Lifecycle Methods
`embed:context/lifecycles.js`
## Forwarding Refs to Context Consumers
`embed:context/forwarding-refs.js`
## Legacy API
> The old context API was marked as legacy in React 16.3 and will be removed in version 17.

View File

@@ -0,0 +1,11 @@
const Button = ({theme, children}) => (
<button className={theme ? 'dark' : 'light'}>
{children}
</button>
);
export default React.forwardRef((props, ref) => (
<ThemeContext.Consumer>
{theme => <Button {...props} theme={theme} ref={ref} />}
</ThemeContext.Consumer>
));

View File

@@ -0,0 +1,20 @@
class Button extends React.Component {
componentDidMount() {
alert(this.props.theme);
}
render() {
const {theme, children} = this.props;
return (
<button className={theme ? 'dark' : 'light'}>
{children}
</button>
);
}
}
export default props => (
<ThemeContext.Consumer>
{theme => <Button {...props} theme={theme} />}
</ThemeContext.Consumer>
);