用 Context 向子组件传值, 如果想在子元素中修改值的话, 可以向下面代码这样把函数塞到 state 里吗,会不会有什么副作用? 除此之外还有别的办法在很深的子组件里更新 value 吗?
const MyContext = React.createContext({
value: 0,
plusOne: () => {},
})
class App extends React.Component{
constructor(props) {
super(props)
this.state = {
value: 0,
plusOne: () => {
this.setState({
value: this.state.value + 1
})
},
}
}
render() {
return (
<div>
<MyContext.Provider value={this.state}>
<Child></Child>
</MyContext.Provider>
</div>
)
}
}
class Child extends React.Component {
render() {
return (
<div>
<Child2></Child2>
</div>
)
}
}
class Child2 extends React.Component {
static contextType = MyContext;
render() {
return (<div>
{this.context.value}
<button onClick={this.context.plusOne}>+1</button>
</div>)
}
}