javascript - 从 React Component 关闭 React Modal

标签 javascript reactjs react-modal

我在 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 请求后关闭 react 模式。

但是,this 是未定义的。

我该怎么做?

最佳答案

问题出在这里

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好好解释一下。

关于javascript - 从 React Component 关闭 React Modal,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56382715/

相关文章:

javascript - 在 Angular Controller 中将 Rails 日期时间更改为字符串

javascript - 在 Laravel blade 中显示代码片段

javascript - CRA 环境变量中的 npmject 收到 undefined 后

javascript - 创建全局数组以从所有组件访问

javascript - 如何在 firebase 数据库中添加 indexOn userId

javascript - 如何阻止 DustJS 将实体转换回普通字符?

javascript - 未定义错误的属性在刷新时消失

javascript - 登录 React 后关闭模态

javascript - 无法将 react 模式呈现为可重用组件