【问题标题】:React how to update another component's state?React 如何更新另一个组件的状态?
【发布时间】:2016-05-12 01:37:57
【问题描述】:

我对反应很陌生,试图让一些组件工作。我有

    ObjectA:React.createClass({
        propTypes: {
           ...

        },

        getInitialState: function() {
            return {
                myState: null
            }
        },

        updateMyState: function(value) {
           this.setState({
               myState: value
           })
        }

        render: function() {
            return (<div className="my-class">'hello' +{this.state.myState}</div>);
          }
    });

    ObjectB:React.createClass({
            propTypes: {
               ...

            },

            render: function() {
                return (<div className="my-class"><ObjectA / >

            </div>);
            }
        });

我想从 ObjectB 更新 ObjectA 的状态。我如何在 ObjectB 中调用 ObjectA 的 updateMyState 方法? 谢谢!

【问题讨论】:

标签: javascript web reactjs react-native frontend


【解决方案1】:

React 的基本思想是单向数据流。这意味着数据只能通过子组件的属性从祖先组件向下共享到其子组件。对于这个简单的示例,我们将类似 Flux 的架构和事件发射器排除在外,因为它根本没有必要。

从外部更改组件状态的唯一方法是更改​​它在父级渲染方法中接收到的道具。所以 myState 实际上会存在于 ObjectB 中,并作为属性提供给 ObjectA。在您的示例中,如下所示:

ObjectA:React.createClass({
    propTypes: {
       ...

    },

    render: function() {
        return (<div className="my-class">'hello' +{ this.props.name }</div>);
      }
});

ObjectB:React.createClass({
    propTypes: {
       ...

    },

    getInitialState: function() {
        return {
            name: null
        }
    },

    onNameChange: function(newName) {
        this.setState({ name: newName })
    },

    render: function() {
        return (
            <div className="my-class">
                <ObjectA name={ this.state.name } />
            </div>
        );
    }
});

【讨论】:

  • 感谢您的详细解答。
猜你喜欢
  • 2017-10-06
  • 1970-01-01
  • 2022-01-19
  • 2020-07-01
  • 2021-10-06
  • 1970-01-01
  • 2019-10-18
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多