Browse Source

Add ref forwarding, lifecycle examples

main
Alex Krolick 7 years ago
parent
commit
7b5764fed5
  1. 12
      content/docs/context.md
  2. 11
      examples/context/forwarding-refs.js
  3. 20
      examples/context/lifecycles.js

12
content/docs/context.md

@ -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.

11
examples/context/forwarding-refs.js

@ -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>
));

20
examples/context/lifecycles.js

@ -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>
);
Loading…
Cancel
Save