context的使用

  1. context是一个上下文环境,
  2. 使用Context提供的provider和consumer组件来实现跨层级的组件数据传递。
  3. 简单使用
    //context.js
    import React from 'react'
    //创建context的实例
    const myContext = React.createContext()
    export default myContext;
    //app.js
    import myContext from './context'
    
    function App(props) {
        //提供生产者,并传入value属性
        return (<myContext.Provider value={{name: 'xiaomi', age: '17'}}>
            <Header/>
        </myContext.Provider>)
    }
    //title.js
    import myContext from '../context'
    
    function Header(props) {
    //在孙组件title里面消费context,而不用通过header这个子组件
        return (<myContext.Consumer>
            {(context) => <p>name:{context.name} age:{context.age}</p>}
        </myContext.Consumer>)

猜你喜欢

转载自www.cnblogs.com/longlongdan/p/10820976.html
今日推荐