【问题标题】:Close ReactModal from ReactComponent从 ReactComponent 关闭 ReactModal
【发布时间】:2019-10-16 08:57:34
【问题描述】:

我在 ReactModal 中有一个 React.Component。

class Course extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      isModalOpen: false,
    }
  }
  handleModalOpen = event => {
    this.setState({ isModalOpen: true })
  }

  handleModalClose = event => {
    this.setState({ isModalOpen: false })
  }

  render() {
     <ReactModal
          isOpen={this.state.isModalOpen}
          onRequestClose={this.handleModalClose}
          contentLabel="Purchase a Course"
          style={customStyles}>
        <CheckoutComponent handleClose={this.handleModalClose}/>
     </ReactModal>

   class CheckoutForm extends React.Component {
    constructor(props) {
        super(props);
    }

    handleSubmit = (ev) => {
       axios.post(`${process.env.API_URL}purchase`, charge)
          .then(function (response) {
              this.props.handleClose();
          }
  }

我想在成功发布 http 请求后关闭反应模式。

但是,this 未定义。

我该怎么做?

【问题讨论】:

标签: javascript reactjs react-modal


【解决方案1】:

问题出在这里

axios.post(`${process.env.API_URL}purchase`, charge)
          // here
    .then(function (response) {
        this.props.handleClose();
    })

您需要使用箭头函数。对于普通函数,this 将是匿名函数的this。使用箭头函数解决了这个问题,你得到了组件的this

axios.post(`${process.env.API_URL}purchase`, charge)
          // arrow function
    .then(response => {
        this.props.handleClose();
    })

This answer解释清楚。

【讨论】:

  • 当然,但我还需要 6 分钟 :-) 我不能接受我认为少于 10 分钟或看到
  • @Dejell,抱歉 ;)
猜你喜欢
  • 2021-08-09
  • 1970-01-01
  • 2016-02-15
  • 1970-01-01
  • 1970-01-01
  • 2020-12-10
  • 2020-08-12
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多