React 初学者求问, 可以往 state 里放 function 吗?

2021-08-30 23:40:06 +08:00
 rabbbit

用 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>)
  }
}
965 次点击
所在节点    问与答
2 条回复
luin
2021-08-31 00:10:05 +08:00
可以的,不过场景简单且层数比较少的话直接挨层传下去就好了。
abbenyyy
2021-08-31 09:02:47 +08:00

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/798946

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX