在一个典型的 React 应用中,数据是通过 props 属性自上而下(由父及子)进行传递的,代码如下
ThemeBtn 中想要获取到ContextSimple 中的 text 属性,需要将 text 属性从 ContextSimple 传递到
ToolBar,再传递到 ThemeBtn,可以想象假如有10层,那将极其繁琐!
Context提供了一种在组件之间共享值的方式,而不必显式地通过组件树的逐层传递 props。
import React, { Component } from 'react';
function ThemeBtn(props) {
return (
<div>{props.theme.text}</div>
)
}
function ToolBar(props) {
return <ThemeBtn {...props}></ThemeBtn>
}
class ContextSimple extends Component {
constructor(props) {
super(props);
this.state = {
text:'按钮'
};
}
render() {
return (
<ToolBar theme={this.state}></ToolBar>
);
}
}
export default ContextSimple;
如何使用 Context
创建一个Context对象
const ThemeContext = React.createContext();
Provider(订阅者):Provider 接收一个 value 属性,传递给消费者组件。
注意:这个value名字是固定的,不能改变,否则后面的消费者组件中获取不到属性值
<ThemeContext.Provider value={this.state}>
Consumer(消费者):这里,React 组件也可以订阅到 context 变更
<ThemeContext.Consumer>
{
value => <div>{value.name}</div>
}
</ThemeContext.Consumer>
Context 完整使用代码:
import React, { Component } from 'react';
// 创建一个Context对象
const ThemeContext = React.createContext();
function ThemeBtn(props) {
return (
<ThemeContext.Consumer>
{
value => <div>{value.name}</div>
}
</ThemeContext.Consumer>
)
}
function ToolBar(props) {
return <ThemeBtn></ThemeBtn>
}
class ContextSimple extends Component {
constructor(props) {
super(props);
this.state = {
name: '按钮'
};
}
render() {
return (
<ThemeContext.Provider value={this.state}>
<ToolBar></ToolBar>
</ThemeContext.Provider>
);
}
}
export default ContextSimple;