React Context 使用笔记

2019-03-18  本文已影响0人  拖着蜗牛看风景

1、在app.js中 需要通过一个静态属性childContextTypes声明提供给子组件的Context对象的属性。

class App extends Component {

    //先利用childContextTypes声明Context对象属性
    static childContextTypes = {
        title: PropTypes.string
    }
}

2、定义要传送的数据

class App extends Component {

    //先利用childContextTypes声明Context对象属性
    static childContextTypes = {
        title: PropTypes.string
    }

    constructor(props) {
        super(props)
        //然后定义要传递的数据
        this.state = {
            title: '这是标题11'
        }
    }
}

3、利用getChildContext 返回要获取的数据

class App extends Component {
    //先利用childContextTypes声明Context对象属性
    static childContextTypes = {
        title: PropTypes.string
    }

    constructor(props) {
        super(props)
        //然后定义要传递的数据
        this.state = {
            title: '这是标题11'
        }
    }
    //最后返回要获取的数据
    getChildContext() {
        return {
            title: this.state.title
        }
    }
}

在需要的组件中如何使用?
子组件使用方法:


import PropTypes from 'prop-types';

class Post extends Component {
  //利用静态属性contextTypes 获取到要用属性
    static contextTypes = {
        title: PropTypes.string
    }
  //利用this.content.title来获取context传递的值, this.content => object
    render() {
        let datas = this.state.list
        return (
            <div>
                {
                    console.log(this.context.title)
                }
            </div>
        )
    }
}
上一篇 下一篇

猜你喜欢

热点阅读