繁体   English   中英

React.js-通过事件处理程序更改所有者组件的状态

[英]React.js - Changing state of owner component by an event handler

这是处理模型更改事件的正确方法吗?

一种。 handleModelChange函数作为onModelChange属性传递给SubClass。

b。 触发模型更改事件时,为了进行重新渲染,SubComponent中的处理程序将更改MainComponent的状态。

var _SomeMixin={
    componentWillMount: function() {
                this.props.options.model.on("MODEL_CHANGED", this.props.onModelChange);
        },
        componentWillUnmount: function() {
                this.props.options.model.off("MODEL_CHANGED", this.props.onModelChange);
        },
    /* more mixin functions */
}

var SubComponent = React.createClass({
            mixins: [_SomeMixin],
            render: function() {                    
                 return (
                    <div>
                    <!-- ... more elements .. >
                    </div>
                );
            }
        });


var MainComponent = React.createClass({
            getInitialState: function() {
                return {MainComponentState: []};
            },
            handleModelChange: function() {
                if (this.isMounted()) {
                    this.setState({MainClassState: this.props.options.model.toJSON()});
                }
            },
            render: function() {
                return (
                    <SubClass options={this.props.options} onModelChange={this.handleModelChange} />
                    );
            }
        });

这是通知父组件内部组件已更改的可能方法之一。 但是这种方法将导致您陷入回调地狱,您每次都必须通过。

更好的解决方案是使用诸如Moreartyjs之类的状态管理库

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM