[英]React.js - Changing state of owner component by an event handler
Is this the correct way to handle the model change event - 这是处理模型更改事件的正确方法吗?
a. 一种。 The handleModelChange function is being passed as onModelChange prop to SubClass.
handleModelChange函数作为onModelChange属性传递给SubClass。
b. b。 When the model change event triggers, for the re-render to occur, the handler from the SubComponent changes the state of the MainComponent.
触发模型更改事件时,为了进行重新渲染,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} />
);
}
});
This is one of possible ways to inform parent component that inner component has been changed. 这是通知父组件内部组件已更改的可能方法之一。 But this approach will lead you to a callbacks hell, that you will have to pass every time.
但是这种方法将导致您陷入回调地狱,您每次都必须通过。
Better solution is to use some state management library like Moreartyjs 更好的解决方案是使用诸如Moreartyjs之类的状态管理库
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.