React之context
# 简介
React组件之间的通信是基于props的单向数据流,即父组件通过props向子组件传值,亦或是子组件执行传入的函数来更新父组件的state,这都满足了我们大部分的使用场景- 一般地,对于兄弟组件之间的通信,是通过它们共同的祖先组件进行的,即 Lifting State Up,官方文档也有介绍。组件一通过事件将状态变更通知它们共同的祖先组件,祖先组再将状态同步到组件二
- 但是,如果组件之间嵌套的比较深,即使提升状态到共同父组件,再同步状态到相应的组件还是需要一层一层的传递下去,可能会比较繁琐
- 在对应的场景中,
context就可以缩短父组件到子组件的属性传递路径
# 例1
import Parent from './Parent'
import ChildOne from '../components/ChildOne'
import ChildTwo from '../components/ChildTwo'
export default class Container extends React.Component {
constructor(props) {
super(props);
this.state = { value: '' }
}
changeValue = value => {
this.setState({ value })
}
getChildContext() {
return {
value: this.state.value,
changeValue: this.changeValue
}
}
render() {
return (
<div>
<Parent>
<ChildOne />
</Parent>
<Parent>
<ChildTwo />
</Parent>
</div>
)
}
}
Container.childContextTypes = {
value: PropTypes.string,
changeValue: PropTypes.func
}
@前端进阶之旅: 代码已经复制到剪贴板
Parent.jsx
import React from "react"
const Parent = (props) => (
<div {...props} />