重新呈现React中的子组件或更改子状态

Re-render child component in React or change child state

本文关键字:状态 组件 React 新呈现      更新时间:2023-12-12

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

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。但在这种情况下,这些都没有帮助。我也想过用新道具重新渲染子组件,但我不能从父组件重新渲染它。

知道我们如何处理儿童状态吗?

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

例如:

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