一旦我收到Modal.jsx内的道具,如何切换模态

问题描述 投票:1回答:1

我有一个模态组件,当用户点击按钮时,当前Modal打开和关闭,我提交一个表单,并将表单道具传递给Modal组件。

有什么办法可以在从父组件接收道具this.props.wrongAnswer后切换Modal吗?

  state = {
    open: false
  };

  onOpenModal = () => {
    this.setState({ open: true });
  };

  onCloseModal = () => {
    this.setState({ open: false });
  };

<div className={className}>

    { this.props.wrongAnswers.length > 0 ? (

      <Modal open={open} onClose={this.onCloseModal}>

            <h4 className="padding-bottom-top blue">Total: {this.props.total} Out of 10</h4>

                {this.props.total !== 10 ?

                <h5 className="padding-bottom">Wrong Answers :</h5>

                :

                <h5>All Answers are Correct</h5>} {asnwersData}

      </Modal>) : 

    (<div> Loading ..</div>)
}
</div>

Modal正在接收以下道具:

          <div> 
             <ShowModal
                total={Total}
                wrongAnswers={wrongAnswersByUser}
            />
          </div>
javascript reactjs
1个回答
1
投票

你可以通过使用componentWillReceiveProps来实现这一目标

将nextProps与当前道具进行比较,如果收到更改,那么setState将打开为true

componentWillReceiveProps(nextProps) {
    if(this.props.wrongAnswer !== nextProps.wrongAnswer) {
        this.setState({open: true});
    }
}

更新:

我在CodeSandBox上做了一个例子

© www.soinside.com 2019 - 2024. All rights reserved.