V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
V2EX 提问指南
rabbbit
V2EX  ›  问与答

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

  •  
  •   rabbbit · 2021-08-30 23:40:06 +08:00 · 943 次点击
    这是一个创建于 941 天前的主题,其中的信息可能已经有所发展或是发生改变。

    用 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>)
      }
    }
    
    2 条回复    2021-08-31 09:02:47 +08:00
    luin
        1
    luin  
       2021-08-31 00:10:05 +08:00   ❤️ 1
    可以的,不过场景简单且层数比较少的话直接挨层传下去就好了。
    abbenyyy
        2
    abbenyyy  
       2021-08-31 09:02:47 +08:00   ❤️ 1
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   我们的愿景   ·   实用小工具   ·   944 人在线   最高记录 6543   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 27ms · UTC 20:57 · PVG 04:57 · LAX 13:57 · JFK 16:57
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.