[英]Reactjs how to change the state of a component from a different component
我有一個react組件,讓我們將其稱為組件1
define([..., /path/component_2.jsx], function(..., Component2) {
var Component1 = React.createClass({
getInitialState: function() {
return {.......};
},
componentDidMount: function() {
.......
dates = ....;
Component2.setState({dates: dates});
}
render: function() { return (<div ...></div>) }
});
}
如您所見,我在此組件中調用Component2.setState。 但我得到一個錯誤,如setState不是一個函數。 我嘗試在組件2中定義自定義函數而不是setState函數,並從組件1調用此函數,但我得到相同的錯誤,'不是函數'。
和組件2:
define([..., ], function(...) {
var Component2 = React.createClass({
getInitialState: function() {
return {.......};
},
render: function() { return (<div ...></div>) }
});
}
所以我想在reactjs中我們只調用一個組件來渲染某些東西(React DOM元素)? 並且不能改變組件狀態?
如果是這樣,我如何從不是第一個孩子或父母的不同組件中更改組件的狀態?
組件不公開暴露其狀態。 同樣重要的是要記住,狀態的范圍是組件的實例 ,而不是它們的定義。
要在組件之間進行通信,您可以推送自己的事件訂閱服務。
var events = new EventEmitter();
// inside Component1
events.emit('change-state', newState);
// inside Component2
events.on('change-state', function(state) {
this.setState(state);
});
但是,這很快就會變得難以管理。
更明智的解決方案是使用Flux 。 它允許您顯式管理整個應用程序的狀態,並在組件內訂閱狀態的不同位的更改。 值得嘗試包圍它。
想要通信的組件應該分派一個動作,這個動作將負責改變商店中的某些東西,你的另一個組件應該訂閱那個商店,並且可以根據變化更新它的狀態。
您可以在兩個組件之間使用共享狀態。 你可以像這樣構建一個“mixin”
app.mixins.DateMixin = {
getInitialState: function ()
return {
dates: []
}
}
};
然后在你的組件中,你可以使用mixins數組包含這個mixins
define([..., /path/component_2.jsx], function(..., Component2) {
var Component1 = React.createClass({
mixins: [app.mixins.DateMixin],
getInitialState: function() {
return {.......};
},
componentDidMount: function() {
.......
dates = ....;
this.setState({dates: dates});
}
render: function() { return (<div ...></div>) }
});
}
define([..., ], function(...) {
mixins: [app.mixins.DateMixin],
var Component2 = React.createClass({
getInitialState: function() {
return {.......};
},
render: function() { return (<div ...></div>) }
});
}
現在,您的組件共享“日期”狀態,您可以在兩個組件中更改/檢查它。 注意:您也可以通過寫入mixin組件以相同的方式共享方法。
編輯:我建議你訪問這個網站http://simblestudios.com/blog/development/react-mixins-by-example.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.