rabbbit
V2EX  ›  问与答

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

  •  
  •   rabbbit · Aug 30, 2021 · 1736 views
    This topic created in 1717 days ago, the information mentioned may be changed or developed.

    用 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 replies    2021-08-31 09:02:47 +08:00
    luin
        1
    luin  
       Aug 31, 2021   ❤️ 1
    可以的,不过场景简单且层数比较少的话直接挨层传下去就好了。
    abbenyyy
        2
    abbenyyy  
       Aug 31, 2021   ❤️ 1
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   5520 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 61ms · UTC 03:45 · PVG 11:45 · LAX 20:45 · JFK 23:45
    ♥ Do have faith in what you're doing.