[英]Updating a react component from a completely separate component
我正在尋找一種方法,可根據對另一個組件的輸入來重新呈現一個組件。 我在沒有Flux / Redux的情況下使用react,並且對項目投入了足夠的精力,我認為這不是我現在可以采取的方向。
我想做的事情看起來像這樣:
class Component1 extends React.Component{
constructor(props){
super(props);
window.global = 0;
this.state = {};
this.changeGlobal = this.changeGlobal.bind(this);
}
changeGlobal(value){
window.global = value;
}
render(){
return (<div>
<a onClick={() => changeGlobal(1)}>One</a>
<a onClick={() => changeGlobal(2)}>Two</a>
<a onClick={() => changeGlobal(3)}>Three</a>
</div>);
}
}
class Component2 extends React.Component
{
constructor(props){
super(props);
this.state = {};
}
render(){
if(window.global === 0){
return <Something/>;
}
if(window.global === 1){
return <SomethingElse/>;
}
etc...
}
}
除了我希望Component2每次更改全局值時都重新渲染Component2。 有誰知道如何實現這一目標?
我設法通過事件實現了這一點:
class Component1 extends React.Component{
constructor(props){
super(props);
this.state = {};
this.changeGlobal = this.changeGlobal.bind(this);
}
changeGlobal(value){
var event = new CustomEvent('myEvent', { detail: value });
document.body.dispatchEvent(event);
}
render(){
return (<div>
<a onClick={() => changeGlobal(1)}>One</a>
<a onClick={() => changeGlobal(2)}>Two</a>
<a onClick={() => changeGlobal(3)}>Three</a>
</div>);
}
}
class Component2 extends React.Component
{
constructor(props){
super(props);
this.state = {};
this.handleEvent = this.handleEvent.bind(this);
}
handleEvent(event) {
this.setState({ value: event.detail});
}
componentDidMount() {
document.body.addEventListener('myEvent', this.handleEvent, false);
}
componentWillUnmount() {
document.body.removeEventListener('myEvent', this.handleEvent, false);
}
render(){
if(this.state.value === 0){
return <Something/>;
}
if(this.state.value === 1){
return <SomethingElse/>;
}
etc...
}
}
Redux的實現完全不同於React,它意味着您可以隨時隨地實現它,對於您只想要的組件,它既不是最佳的編寫代碼也不是最佳實踐,但是仍然是只是說說可能性。 而且,如果您想正確地更新組件(還進行更改顯示),則需要更改該組件狀態,否則,即使您成功地將一個值從一個組件傳遞到另一個組件,也永遠不會呈現更改。
我不是專家,但是我的建議是將Component2的狀態鏈接到它的props,以便可以通過外部組件對其進行修改。 最常見的方法是將兩個組件都包裝在父組件中,然后,每當Component1中的值更改時,它都會觸發一個事件(或函數),該事件(或函數)將由父組件處理,然后后者會將該值傳遞給Component2。它是道具,並且(可能)觸發了一個將改變Component2狀態的函數。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.