事件对象/参数是否自动传递给React事件处理程序



答案可能是肯定的。因为它有效,而且我们整天都在使用它,我知道。我要求100%肯定,并为未来的React学习者做好准备。我在React的官方文档中看不到它,只是给出了一个将多个参数与事件对象一起传递给事件处理程序的例子。例如:正如您所看到的onFormSubmit,尽管在JSX引用中没有event参数,但它可以访问事件对象,以便在执行时执行某些操作(在本例中阻止页面刷新(。

如果将onFormSubmit编写为像onChange处理程序那样的内联箭头函数,则需要传递事件对象,那么它不是自动的。


class SearchBar extends React.Component {
constructor(props) {
super(props)
this.state = { term:''}
this.onFormSubmit = this.onFormSubmit.bind(this)
}
onFormSubmit(event) {
event.preventDefault()
console.log(this.state.term) 
}

render() {
return (
<div className="ui segment" >
<form onSubmit={this.onFormSubmit} className="ui form" >
<div className="field" >
<label>Search</label>
<input type="text" 
value = {this.state.term} 
onChange={event => this.setState({ term: event.target.value })} />
</div>
</form>
</div>
)
}
}
export default SearchBar

您已经为onChange事件处理程序定义了函数,该函数调用传递必要参数implicity的submit方法。

React中的event处理程序没有什么特别之处。每个函数(如果定义(都是这样工作的。

const a = [1, 2, 3];
function print(elem, idx) {
console.log(elem, idx);
}
// here you have defined the print function.
// the elem and idx are passed implicitly to run the function.
a.forEach(print);
or 
// now, rather than defining the function here.
// you have used another arrow function.
// then you need to pass the arguments explicitly.
a.forEach((elem, idx) => print(elem, idx));

React使用Synthetic Events来处理事件,但这是回调处理程序的一般工作方式。如果在那里使用函数引用,那么event对象是传递给函数的唯一参数。因此,如果事件对象是您想要获得的唯一参数,那么您不需要使用箭头函数。

如果要在传递event对象的同时传递其他变量,则可以使用箭头函数。

<form onSubmit={e => this.onFormSubmit(e, otherVar)} className="ui form" >

因此,回调获取事件参数,并将其与其他变量一起传递给处理程序函数。

onFormSubmit(event, otherVar) {
event.preventDefault()
console.log(otherVar) 
}

最新更新