
简介
context是React发布的一个比较高级的功能,但是还是实验阶段,很有可能会删除或更改,所以不推荐频繁的、大范围的使用。其使用的原因在于解决了在React中传递参数复杂,且不能跨组件、跳跃的传递的问题。react-redux就是利用context统一的进行状态管理,在说context之前我们可以先看看props传递参数的方法。
props
在react中,数据通过数据流的方式从上而下的传输,使用组件时,组件间的props从上到下的传递。官方给的示例是
class App extends React.Component {
render() {
return <Toolbar theme="dark" />;
}
}
function Toolbar(props) {
return (
<div>
<ThemedButton theme={props.theme} />
</div>
);
}
function ThemedButton(props) {
return <Button theme={props.theme} />;
}
从上面的代码我们可以知道,如果我们想将Toolbar component中的theme参数传给ThemedButton,每一过经过ThemedButton的组件都需要携带theme参数,这是非常麻烦的。如本示例中就要经过两步才能传递我们想传递的参数。
context
使用context,我们就可以不通过中间过程达到传递参数的目的,简而言之,context可以越级传递数据到你想传递数据的组件。
使用方法
- 从npm安装prop-types依赖
npm install prop-types --save
- 引入PropTypes对象
import PropTypes from 'prop-types'
下面是一个通过context传递参数的示例
class App extends Component {
static childContextTypes = {
themeColor: PropTypes.string,
}
getChildContext() {
return {
themeColor: this.state.themeColor
}
}
constructor() {
super()
this.state = {
themeColor:'red'
}
}
render() {
return (
<div>
<Title></Title>
</div>
)
}
}
class Title extends Component {
static contextTypes = {
themeColor: PropTypes.string
}
render() {
return (
<h1 style={{ color: this.context.themeColor }}>这是要改变颜色的标题</h1>
)
}
}
示例代码中通过添加静态 childContextTypes和getChildContext() 到App中,React 自动向下传递数据然后在组件树中的任意组件,子组件可以使用静态方法 contextTypes访问数据,数据存在context中 。
- 在传递参数的过程中需要通过引入的PropTypes对象进行类型的判断
- prop传递不仅可以传递参数,还可以传递方法
总结
想通过context 越级
的从父组件传递给子组件。父组件需要定义childContextTypes进行类型检查,getChildContext()传递参数,想要接收数据的组件通过contextTypes进行类型检查,传递过来的参数通过context使用。