子组件未调用父组件函数

时间:2018-07-01 05:24:18

标签: javascript reactjs

所以我有一个父组件和一个子组件。我在绑定到父级的父级组件中有一个函数,并将其传递给子级以供子级使用。但是,使用该功能的子组件中的X按钮无法调用该功能。

在标记重复项之前,请先查看我的代码,因为我查看了其他帖子,这些帖子不足以解决我的问题。

class SimulatorProgressPopup extends React.Component {
    constructor(props) {
        super(props);
        this.state = {show: props.show, data: props.data};
    }

    componentWillReceiveProps(nextProps) {
        this.setState({show: nextProps.show, data: nextProps.data});
    }

    render() {
        return (<div style={{display: this.state.show, position: "fixed", width: "500px", height:"300px", left:"50%", top:"50%", transform: "translate(-50%, -50%)", border: "1px solid black"}}>
            <button onClick={this.props.close}>X</button>
        </div>)
    }
}

class SingleSimulatorProgress extends React.Component {
    constructor(props) {
        super(props);
        this.state = {showPopup: false, data: props.data};
        this.popup = this.popup.bind(this);
        this.popupClose = this.popupClose.bind(this);
    }

    componentWillReceiveProps(nextProps) {
        this.setState({data: nextProps.data});
    }

    popup() {
        this.setState({showPopup: true});
    }

    popupClose() {
        this.setState({showPopup: false});
    }

    render() {
        return (<tr onClick={this.popup}>
            <td>{this.state.data.leId.substring(this.state.data.leId.length - 3, this.state.data.leId.length)}</td>
            <td className={this.state.data.status}>{this.state.data.status}</td>
            <td>{this.state.data.noOfFailedRequest}</td>
            <td>{this.state.data.requestSent}</td>
            <td>{this.state.data.responseReceived}</td>
            <td>{this.state.data.failureRate}</td>
            <td>{this.state.data.avgReqLatencyInMilis}</td>
            <SimulatorProgressPopup show={this.state.showPopup ? "block" : "none"} data={this.state.data} close={this.popupClose}/>
        </tr>)
    }
}

1 个答案:

答案 0 :(得分:1)

您的问题是,您没有阻止事件冒泡到父侦听器(整行)。所以您需要做的就是防止这种情况

popupClose(e) {
    e.stopPropagation();
    this.setState({showPopup: false});
}

如果您不执行此操作,则实际上是在一个渲染周期内显示show为假,然后show为true。因此弹出窗口保持不变。

Here's it live in action if you'd like to see