在我的 React 组件中,我有一个带有 onSubmit 函数的表单
<form className="form-horizontal" name="taskForm" onSubmit={this.submitTask}>
submitTask(e) {
e.preventDefault();
console.log(this.props); // undefined
console.log(this) // window object
}
出于某种原因this.props
当我使用表单 onSubmit 时,不在范围内。当我 console.log(this.props)
在构造函数中,props 正常注销。
当我 console.log(this)
它是窗口对象。如何获取 React 组件的作用域?
最佳答案
这是一个更广泛的问题,因为当您使用其他组件事件(例如 onClick、onChange、onSubmit)时,您会注意到与此类似的行为
在文档中有关于它的注释:
https://facebook.github.io/react/docs/reusable-components.html#no-autobinding
Methods follow the same semantics as regular ES6 classes, meaning that they don't automatically bind this to the instance. You'll have to explicitly use .bind(this) or arrow functions =>.
正如所描述的,您必须绑定(bind)这些方法或使用箭头函数。 如果您选择绑定(bind),那么您可以在构造函数中绑定(bind)或严格在渲染组件中绑定(bind)。
在构造函数中:
constructor(props) {
super(props);
this.submitTask = this.submitTask.bind(this);
}
在渲染组件中:
<form className="form-horizontal" name="taskForm" onSubmit={this.submitTask.bind(this)}>
使用箭头函数,您可以将submitTask内容传递给箭头函数:
<form className="form-horizontal" name="taskForm" onSubmit={e => {
e.preventDefault();
console.log(this.props); // undefined
console.log(this) // window object
}}>
关于reactjs - 为什么这不在 React 表单 onSubmit 函数的范围内?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35881959/