我在 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/