父组件
class List extends Componet(){
constructor(props){
super(props)
}
static childContextTypes = { // 必须写
color: PropTypes.string
}
getChildContext(){
return {
color: 'res'
}
}
}
子组件
class ListItem extends Componet(){
constructor(props){
super(props)
}
stati contextTypes = { // 必须写
color: PropTypes.string
}
render(){
console.log(this.context.color) // 就可用父组件的数据了
}
}
React context 用法
最新推荐文章于 2025-01-09 16:17:47 发布
本文介绍了一个使用React的上下文API实现父子组件间状态共享的例子。通过定义父组件的`childContextTypes`和`getChildContext`方法以及子组件的`contextTypes`,实现了子组件直接访问父组件的状态。
1301

被折叠的 条评论
为什么被折叠?



