【问题标题】:React child element calling the parent element, on value在值上反应调用父元素的子元素
【发布时间】:2016-04-04 00:23:07
【问题描述】:

我正在尝试创建一个 MessageBox(Modal Box) 元素,该元素获取输入以形成 Modal Box,MessageBox 中的 close 方法不会调用父级 close 并反过来让 Modal 消失,有什么帮助吗??

导出默认类 MessageBox 扩展组件{

constructor(props) {
    super(props);
    this.close = this.close.bind(this);
}

close(){
    this.props.callbackParent;
}

render(){
    return (
        <div>
            <Modal show={this.props.visibility} onHide={this.close}>
                <ModalHeader closeButton>
                    <ModalTitle>{this.props.msgHeader}</ModalTitle>
                </ModalHeader>
                <ModalBody>{this.props.msgBody}</ModalBody>
            </Modal>
        </div>
    );
}

}

导出默认类产品扩展组件{

constructor(props) {
    super(props);
    this._initState = {
        showModal: false
    }
    this.state = this._initState;
    this.open = this.open.bind(this);
    this.close = this.close.bind(this);
}

open(){
    this.setState(
        { showModal: true }
    );
}

close(){
    this.setState(
        { showModal: false }
    );
}

render(){
    return (
        <div>
            <Button bsStyle="primary" bsSize="large" onClick={this.open}>
                Go!!!
            </Button>
            <MessageBox visibility={this.state.showModal} msgHeader='Header goes here ...' msgBody='Overlay message body goes here ..' callbackParent={this.close}/>
        </div>
    );
}

};

【问题讨论】:

  • MessageBox 的 close 函数中缺少括号。您需要 this.props.callbackParent() 才能实际调用它

标签: reactjs reactjs-flux


【解决方案1】:

我已经通过这个工作了

export default class MessageBox extends Component{

constructor(props) {
    super(props);
}

render(){
    return (
        <div>
            <Modal show={this.props.visibility} onHide={this.props.callbackParent}>
                <ModalHeader closeButton>
                    <ModalTitle>{this.props.msgHeader}</ModalTitle>
                </ModalHeader>
                <ModalBody>{this.props.msgBody}</ModalBody>
                <ModalFooter>
                    <Button onClick={this.props.callbackParent}>Close</Button>
                </ModalFooter>
            </Modal>
        </div>
    );
}

}

【讨论】:

    【解决方案2】:

    您似乎在 MessageBox 的 close 方法中缺少括号。

    this.props.callbackParent; 
    

    应该是

    this.props.callbackParent();
    

    (感谢@azium)的答案。

    【讨论】:

    • 感谢您抽出宝贵时间回复,谢谢!
    猜你喜欢
    • 2015-07-06
    • 2011-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-01-17
    • 1970-01-01
    相关资源
    最近更新 更多