Javascript “与”的区别是什么;onClick={()=>;this.props.onClick()}和onClick={props.onClick}?

Javascript “与”的区别是什么;onClick={()=>;this.props.onClick()}和onClick={props.onClick}?,javascript,reactjs,Javascript,Reactjs,我在学习React教程 请注意以下两个代码段中的“onClick”属性 在下面截图中,为其分配了一个arrow函数,该函数调用在props中传递给它的onClick()函数 class Square extends React.Component { render() { return ( <button className="square" onClick={() => this.props.onCli

我在学习React教程

请注意以下两个代码段中的“onClick”属性

在下面截图中,为其分配了一个arrow函数,该函数调用在props中传递给它的onClick()函数

  class Square extends React.Component {
  render() {
    return (
      <button
        className="square"
        onClick={() => this.props.onClick()}
      >
        {this.props.value}
      </button>
    );
  }
}
function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}
类Square扩展了React.Component{
render(){
返回(
this.props.onClick()}
>
{this.props.value}
);
}
}
但是,当类组件转换为功能组件时,onClick属性只分配给props中传递的onClick函数的引用

  class Square extends React.Component {
  render() {
    return (
      <button
        className="square"
        onClick={() => this.props.onClick()}
      >
        {this.props.value}
      </button>
    );
  }
}
function Square(props) {
  return (
    <button className="square" onClick={props.onClick}>
      {props.value}
    </button>
  );
}
功能广场(道具){
返回(
{props.value}
);
}

为什么会这样?我很困惑。

在基于类的组件中,道具是类实例本身的属性。因此,您可以通过
访问它们。在函数组件中,道具作为参数传递到函数中

您可以阅读基于类和功能组件的基础知识


另外,欢迎来到这个网站

当您使用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
}


两者都只是两种方法。箭头函数法和函数原型法

这里有一个很好的差异解释。我不明白您为什么在函数原型方法中添加构造函数。原始代码中没有构造函数。在函数原型方法中使用构造函数将有助于您在方法中读取此.state。您可以在功能组件中阅读this.props和this.state。