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

时间:2016-04-02 21:51:28

标签: javascript reactjs

例如,我们有一个组件(这是一个孩子):

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>
        );
    }
}

我们有父母组成部分:

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>
        )
    }
}

所以我只想要能够从父母打开模态元素,然后能够从孩子改变相同的子状态。 我尝试使用componentWillReceiveProps()并使用npm包:react-komposer。但在这种情况下,这些都没有用。 我还考虑过使用新道具重新渲染子组件,但我不能从父组件重新渲染它。

任何想法我们如何操纵孩子的状态?

1 个答案:

答案 0 :(得分:3)

如果你想改变父组件中的模态状态,你应该在那里处理它(在父组件上)。在这种情况下,Child可以是一个无状态组件,它调用父项中的函数。 有没有理由不这样做?

例如:

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