简体   繁体   English

在React中重新渲染子组件或更改子状态

[英]Re-render child component in React or change child state

For example, we have a component (this is a child): 例如,我们有一个组件(这是一个孩子):

class Child extends React.Component {
    constructor(props) {
        super(props);
        this.state = {show: props.show || false};
        this.close = this.close.bind(this);
        this.open = this.open.bind(this);
    }   
    close() {
        this.setState({show: false});
    }

    open() {
       this.setState({show: true});
    }
    render() {
        return (
            <div>
                <Button onClick={this.open}>Open</Button>
                <Modal show={this.state.show} onHide={this.close}>
                    .........
                        <Button onClick={this.close}>Close</Button>
                </Modal>
            </div>
        );
    }
}

and we have parents component: 我们有父母组成部分:

class Parents extends React.Component {
    constructor(props) {
        super(props);
        this.state = {show: false};
        this.open = this.open.bind(this);
    }
    open() {
        this.setState({show: true});
    }
    render() {
        return (
            <div>
                <Button onClick={this.open}>open</Button>
                <Child show={this.state.show}/>
            </div>
        )
    }
}

So i just want be able to open modal element from parents and then be able to change the same child state from child. 所以我只想要能够从父母打开模态元素,然后能够从孩子改变相同的子状态。 I tried use componentWillReceiveProps() and also i use npm package: react-komposer . 我尝试使用componentWillReceiveProps() ,我也使用npm包: react-komposer But none of that is helpful in this case. 但在这种情况下,这些都没有用。 I also thought about re-render child component with new props, but i can't re-render it from parents component. 我还考虑过用新道具重新渲染子组件,但我无法从父组件重新渲染它。

Any idea how can we manipulate with child state? 任何想法我们如何操纵孩子的状态?

If you wanna change the modal state in parents components, you should just handle it there (on the parent component). 如果你想改变父组件中的模态状态,你应该在那里处理它(在父组件上)。 The Child in this case could be a stateless component that invokes the functions from the parent. 在这种情况下, Child可以是一个无状态组件,它从父级调用函数。 Is there a reason not to do it this way? 有没有理由不这样做?

For example: 例如:

<Button onClick={props.open}>Open</Button>
<Modal show={props.show} onHide={props.close}>
       .........
       <Button onClick={props.close}>Close</Button>
</Modal>

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

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