【问题标题】:How to change a property value of this.state in the child component's child如何在子组件的子组件中更改 this.state 的属性值
【发布时间】:2019-11-27 22:33:12
【问题描述】:

无法从子组件的子组件中弄清楚如何在父组件的 this.state 中设置特定属性。我知道如何将函数传递给子组件并让它影响传递它的父组件,但是将函数传递给子组件并在其父组件的 this.state 中设置值似乎很棘手。所以这是三层而不是两层。

我不一定需要代码或示例,尽管它们会受到欢迎。我只需要正确的角度来解决这个问题。我是否只是将一个函数从顶级父级(通过道具)传递给子级,而子级从不调用它,而只是通过道具将它通过管道传递给它的子级,在点击事件中实际调用它?不确定如何连接回父级的父级并更改 this.state 值

【问题讨论】:

  • 是的,在子链中向下传递函数是在 vanilla react 中管理此问题的预期方式。如果您发现您的状态管理需求变得足够复杂以至于这已经不够用,请考虑研究像 Redux 这样的状态管理框架。
  • 我想你回答了我的问题,或者至少验证了如何解决这个问题,这是我问的。我会弄清楚如何编码。如果您想在答案中发表评论,我将其标记为已回答。

标签: reactjs ecmascript-6


【解决方案1】:

您可以使用Context API。您还可以使用商店,例如 Redux。将数据存储在 redux 存储中,而不是组件中,并使用 child 中的操作来更改数据

const Context = React.createContext();

class Parent extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
            color: 'white'
        };
    }

    render() {
        return (
            <Context.Provider value={this.setState.bind(this)}>
                <React.Fragment>
                    <div style={{background: this.state.color}}>123</div>
                    <Child1/>
                </React.Fragment>
            </Context.Provider>
        );
    }
}

class Child1 extends React.Component {
    render() {
        return (
            <span>
                child1
                <Child2/>
            </span>
        );
    }
}

class Child2 extends React.Component {
    render() {
        return (
            <Context.Consumer>
                {(setState) => (
                    <button onClick={() => { setState({color: 'red'}); }}>child2</button>
                )}
            </Context.Consumer>
        );
    }
}

ReactDOM.render(<Parent/>, document.querySelector('#app'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script>

<div id="app"></div>

【讨论】:

  • 我只是对redux一无所知。那在名单上。但我很欣赏你的建议,并已经标记了你的答案,最终,这可能是在复杂情况下做到这一点的最佳方式。
【解决方案2】:

是的,在子链中向下传递函数是在 vanilla react 中管理此问题的预期方式。

如果您发现自己的状态管理需求变得复杂到无法满足要求,请考虑研究像 Redux 这样的状态管理框架。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 2019-07-28
    • 1970-01-01
    • 2020-03-08
    • 2020-12-19
    • 2021-12-25
    • 2016-07-27
    相关资源
    最近更新 更多