我正在学习React教程here
请注意以下两个代码片段中的"onClick“属性。
在下面的片段中,一个箭头函数被分配给它,该函数调用在props中传递给它的onClick()函数。
class Square extends React.Component {
render() {
return (
<button
className="square"
onClick={() => this.props.onClick()}
>
{this.props.value}
</button>
);
}
}但是,当类组件被转换为功能组件时,onClick属性仅被分配给传递给props的onClick函数的引用。
function Square(props) {
return (
<button className="square" onClick={props.onClick}>
{props.value}
</button>
);
}为何会这样呢?我很困惑。
发布于 2020-08-08 01:54:56
发布于 2020-08-08 02:18:00
当您使用ES6类定义组件时,常见的模式是将事件处理程序作为类上的方法。
函数原型方法:
function Square(props) {
return (
<button className="square" onClick={props.onClick}>
{props.value}
</button>
);
}
and you bind the state() in constructor using this:
constructor(props) {
super(props);
// This binding will help you to read "this." in the function
this.onClick = this.onClick.bind(this);
}
onClick() {
// u can read this here
}箭头函数方法
做同样事情的另一种方法是:在下面的方法中,你不必绑定构造函数,而是使用箭头函数。在函数内部,this.将具有状态。
onClick = () => {
// u can read this here
}两者都只是两种方法。箭头函数方法和函数原型方法
https://stackoverflow.com/questions/63306902
复制相似问题