【问题标题】:Re-render child component in React or change child state在 React 中重新渲染子组件或更改子状态
【发布时间】:2016-04-02 21:51:28
【问题描述】:

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

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

知道如何使用子状态进行操作吗?

【问题讨论】:

标签: javascript reactjs


【解决方案1】:

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

例如:

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

【讨论】:

    猜你喜欢
    • 2020-04-07
    • 1970-01-01
    • 2020-05-04
    • 2018-06-04
    • 2017-10-04
    • 2020-06-26
    • 2020-06-26
    • 2019-01-08
    • 2023-03-05
    相关资源
    最近更新 更多