一、当我们父组件中嵌套了非常多子组件,然后子组件的数据又依赖父组件的传入,然后子组件中又嵌套孙组件,那么想要在父组件中传值给孙组件就是个技术活了,如果一直用props传的话,那就是套娃一样了,所以我们可用到context来当一个中间桥梁了。
class Index extends Component {
render () {
return (
<div>
<Header />
<Main />
</div>
)
}
}
class Header extends Component {
render () {
return (
<div>
<h2>This is header</h2>
<Title />
</div>
)
}
}
class Main extends Component {
render () {
return (
<div>
<h2>This is main</h2>
<Content />
</div>
)
}
}
class Title extends Component {
render () {
return (
<h1>React.js 小书标题</h1>
)
}
}
class Content extends Component {
render () {
return (
<div>
<h2>React.js 小书内容</h2>
</div>
)
}
}
ReactDOM.render(
<Index />,
document.getElementById('root')
)
复制代码
例如我想要修改content组件内容的主题颜色时,使用context就很轻松办到了
// 父组件中的操作
class Index extends Component {
static childContextTypes = {
themeColor: PropTypes.string
}
constructor () {
super()
this.state = { themeColor: 'red' }
}
getChildContext () {
return { themeColor: this.state.themeColor }
}
render () {
return (
<div>
<Header />
<Main />
</div>
)
}
}
复制代码
getChildContext这个方法就是设置context了,context是个对象来的,那么我们的构造器中首先先定义一个属性themeColor,接着利用getChildContext来设置一个context,但是需要注意的是一定要使用childContextTypes来对context返回的对象进行校验,这个是必须要的。
二、那么我们在孙组件中应该如何使用呢,上代码
class Title extends Component {
static contextTypes = {
themeColor: PropTypes.string
}
render () {
return (
<h1 style={{ color: this.context.themeColor }}>React.js 小书标题</h1>
)
}
}
复制代码
我们想要使用到context的话就一定要用到contextTypes来声明和验证你需要获取的状态的类型,它也是必写的,如果你不写就无法获取 context 里面的状态。然后在render中就可以使用了this.context.themeColor,你学废了吗
© 版权声明
文章版权归作者所有,未经允许请勿转载。
THE END