假设我们有一个处理程序(在我们的类中扩展了 react 中的组件)
whatever = () => {
//Something
}
当我们做的时候
onClick="{()=> this.whatever}"
,当 javascript 处理我们的代码(或编译/读取)时,在点击事件发生之前不会执行此代码
对比
{this.whatever} 应在 javascript 到达此点或读取此点后立即执行。
因此,我们一般使用这个{()=> this.whatever}
我们希望事件在有人说点击后发生?和 {this.whatever}
JS编译时会立即执行处理程序/方法吗?
[更新]
在我按照一些教程制作的 React 应用程序中,我们有箭头函数处理程序说 whatever
像这样传递给子组件 <BuildControls whatever={this.whatever} />
.在子组件中我们做 <button onClick={props.whatever} />
哪个有效。那我们为什么不做 <button onClick={() => props.whatever} />
(如果我们采用后面的方法,onClick 事件也不起作用)
最佳答案
{this.whatever}
与 {this.whatever()}
不同
在 javascript(和大多数其他语言)中执行您需要括号的函数。如果您使用 {this.whatever}
,您会将一个函数作为参数传递给 prop,当用户单击时,传递的函数将被触发。
下面是显示差异的示例代码。
const whatever = () => {
return "I log from function";
}
console.log(whatever); // returns function
console.log((() => whatever)); //returns a function that returns a function
console.log(whatever()); // runs the function
示例 React 应用 ( Live Demo )
import React from "react";
import ReactDOM from "react-dom";
import "./styles.css";
class CustomButton extends React.Component {
render() {
console.log("passed function", this.props.onButtonClick);
return (
<button
onClick={e => this.props.onButtonClick(e, "something from button")}
>
{this.props.name}
</button>
);
}
}
class App extends React.Component {
constructor() {
super();
this.test1 = this.test1.bind();
}
test1(e) {
// I'm a regular function
// I need to be bind
e.preventDefault();
console.log("test 1");
}
test2(e) {
// I'm a regular function
// I need to be bind
e.preventDefault();
console.log("test 2");
}
test3 = e => {
// I'm an arrow function
// I don't loose context of this
// so I don't need to be bind
e.preventDefault();
console.log("test 3");
};
test4 = (e, text) => {
// I am passed down to child component
// run with an extra argument
e.preventDefault();
console.log(text);
};
render() {
return (
<div className="App">
<button onClick={this.test1}>Test 1</button>
<button onClick={this.test2.bind(this)}>Test 2</button>
<button onClick={this.test3}>Test 3</button>
<CustomButton onButtonClick={this.test4} name="Test 4" />
</div>
);
}
}
const rootElement = document.getElementById("root");
ReactDOM.render(<App />, rootElement);
需要阅读的一些文档
关于javascript - {()=> (this.whatever)} 与 {this.whatever},我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50916879/