用 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>) } }
![]() | 1 luin 2021-08-31 00:10:05 +08:00 ![]() 可以的,不过场景简单且层数比较少的话直接挨层传下去就好了。 |
![]() | 2 abbenyyy 2021-08-31 09:02:47 +08:00 ![]() 可以的,react 文档里面提到的[在嵌套组件中更新 Context]( https://zh-hans.reactjs.org/docs/context.html#updating-context-from-a-nested-component),就是你使用的方法。 |