繁体   English   中英

从完全独立的组件更新反应组件

[英]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.

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