简单地写一个例子,使用 React Context 传递数据分成以下三个步骤:

    1. 使用 React.createContext 函数创建一个 Context
    2. 使用 Provider 传递数据
    3. 使用 this.context 或者 Consumer 接收数据

    class 可以使用可以使用 this.context 拿到数据,只需提前拿到 Context 实例即可,拿的方式下面两种等价

    • class 组件内部:static contextType = ThemeContext
    • class 组件外面:Component.contextType = ThemeContext

    函数组件只能通过 Consumer 方式拿到数据,示例如下

    1. function Grandfather(){
    2. return <Father />
    3. }
    4. function Father(){
    5. return <Son />
    6. }
    7. function Son(){
    8. return (
    9. <TextContext.Consumer>
    10. {(value)=><Grandson value={value}/>}
    11. </TextContext.Consumer>
    12. )
    13. }
    14. function Grandson(props){
    15. return <h1>{props.value}</h1>
    16. }
    17. const TextContext = React.createContext('Hi')
    18. function App(){
    19. return (
    20. <TextContext.Provider value='Hello'>
    21. <Grandfather />
    22. </TextContext.Provider>
    23. )
    24. }
    25. ReactDOM.render(<App />,document.querySelector('#root'))

    「@浪里淘沙的小法师」