简单地写一个例子,使用 React Context 传递数据分成以下三个步骤:
- 使用 React.createContext 函数创建一个 Context
- 使用 Provider 传递数据
- 使用 this.context 或者 Consumer 接收数据
class 可以使用可以使用 this.context 拿到数据,只需提前拿到 Context 实例即可,拿的方式下面两种等价
- class 组件内部:static contextType = ThemeContext
- class 组件外面:Component.contextType = ThemeContext
函数组件只能通过 Consumer 方式拿到数据,示例如下
function Grandfather(){return <Father />}function Father(){return <Son />}function Son(){return (<TextContext.Consumer>{(value)=><Grandson value={value}/>}</TextContext.Consumer>)}function Grandson(props){return <h1>{props.value}</h1>}const TextContext = React.createContext('Hi')function App(){return (<TextContext.Provider value='Hello'><Grandfather /></TextContext.Provider>)}ReactDOM.render(<App />,document.querySelector('#root'))
「@浪里淘沙的小法师」
