mirror of
https://github.com/reactjs/react.dev.git
synced 2026-02-23 20:23:08 +00:00
Add ref forwarding, lifecycle examples
This commit is contained in:
@@ -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
Normal file
11
examples/context/forwarding-refs.js
Normal 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>
|
||||
));
|
||||
20
examples/context/lifecycles.js
Normal file
20
examples/context/lifecycles.js
Normal 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>
|
||||
);
|
||||
Reference in New Issue
Block a user