Context 通过组件树提供了一个传递数据的方法,从而避免了在每一个层级手动的传递 props 属性。
使用步骤
- 引入
let ThemeContext = React.createContext()
ThemeContext 得到一个对象 = {Provider(提供者), Consumer(消费者)}
- 父组件向下传值
export default class TextPage extends Component {
constructor(props) {
super(props)
this.state = {
color: 'red'
}
}
setColor = (color) => {
this.setState({
color
})
}
render () {
let value = {color: this.state.color, setColor: this.setColor}
return (
<ThemeContext.Provider value={value}>
<div style={{width: '100px', border: `4px solid ${this.state.color}`, padding: '10px'}}>
TextPage
<Main></Main>
</div>
</ThemeContext.Provider>
)
}
}
- 子孙组件获取使用(类组件)
// 子组件
class Main extends React.Component {
static contextType = ThemeContext // 给类组件添加一个静态属性 contextType, 指向 ThemeContext, 然后这个组件实例上会多一个 this.context = Provider 里的 value
render () {
return (
<div style={{padding: '10px', border: `4px solid ${this.context.color}`}}>
Main
<Title></Title>
</div>
)
}
}
// 孙组件
class Title extends React.Component {
static contextType = ThemeContext
render () {
return (
<div style={{padding: '10px', border: `4px solid ${this.context.color}`}}>
Title
<button onClick={() => this.context.setColor('red')}>红</button>
<button onClick={() => this.context.setColor('yellow')}>黄</button>
</div>
)
}
}
- 子孙组件获取使用(函数组件)
function Main(props) {
return (
<ThemeContext.Consumer>
{
value => {
return <div style={{padding: '10px', border: `4px solid ${value.color}`}}>
Main
<Title></Title>
</div>
}
}
</ThemeContext.Consumer>
)
}