Javascript 问题:()=>;vs函数()

Javascript 问题:()=>;vs函数(),javascript,reactjs,arrow-functions,Javascript,Reactjs,Arrow Functions,跟随他们网站上的ReactJS教程 var Comment = React.createClass({ render: function() { return ( <div className="comment"> <h2 className="commentAuthor"> {this.props.author} </h2> {this.props.children}

跟随他们网站上的ReactJS教程

var Comment = React.createClass({
  render: function() {
    return (
      <div className="comment">
        <h2 className="commentAuthor">
          {this.props.author}
        </h2>
        {this.props.children}
      </div>
    );
  }
});

var CommentList = React.createClass({
  render: () => {
    return (
      <div className="commentList">
        <Comment author="Pete Hunt">This is one comment</Comment>
        <Comment author="Jordan Walke"> This is *another* comment</Comment>
      </div>
    );
  }
});

var CommentForm = React.createClass({
  render: () => {
    return (
      <div className="commentForm">
        Comment Form
      </div>
    );
  }
});

var CommentBox = React.createClass({
  render: () => {
    return (
      <div className="commentBox">
        <h1>Comments</h1>
        <CommentList />
        <CommentForm/>
      </div>
    );
  }
});

ReactDOM.render(
  <CommentBox />,
  document.getElementById("content")
);
var Comment=React.createClass({
render:function(){
返回(
{this.props.author}
{this.props.children}
);
}
});
var CommentList=React.createClass({
渲染:()=>{
返回(
这是一条评论
这是另一个评论
);
}
});
var CommentForm=React.createClass({
渲染:()=>{
返回(
评论表
);
}
});
var CommentBox=React.createClass({
渲染:()=>{
返回(
评论
);
}
});
ReactDOM.render(
,
document.getElementById(“内容”)
);
但是,如果我在第一个组件注释中使用箭头符号,即:

(*params*)=>{}

代替常规函数声明符号,即:

函数(*params*){}

chrome解释器将抛出以下错误:

未捕获的TypeError:无法读取未定义的属性“props”



有人能解释一下这件事吗?

箭头函数不会绑定
这件事。因此,如果将
渲染
函数创建为箭头函数,则
将不会绑定到当前组件


因此,对于
render
和属于您的组件并且需要作为
this
访问组件的其他方法,您需要使用实际函数。不过,您可以对嵌套函数使用箭头函数(在这里使用箭头函数更有意义)。

箭头函数不会绑定
。因此,如果将
渲染
函数创建为箭头函数,则
将不会绑定到当前组件


因此,对于
render
和属于您的组件并且需要作为
this
访问组件的其他方法,您需要使用实际函数。不过,您可以将箭头函数用于嵌套函数(在这里使用它们更有意义)。

箭头函数具有静态词法,这可以通过读取它们的声明来确定。在英语中,不能通过方法调用、调用、应用或绑定来修改它们的此值。由于“this”在创建函数时未定义,因此无论如何调用它,它都将始终未定义。您不能以假设的方式将
this
=>
一起使用,
({foo:x=>this}).foo();//==窗口
Arrow函数具有静态词法,可通过读取其声明来确定。在英语中,不能通过方法调用、调用、应用或绑定来修改它们的此值。由于“this”在创建函数时未定义,因此无论如何调用它,它都将始终未定义。您不能以假设的方式将
this
=>
一起使用,
({foo:x=>this}).foo();//==窗口
非常有意义。非常值得一提。旁注:如果真正的函数编写起来很繁重,那么就使用ES6类并将React组件作为类来编写。少一点打字,很有意义。非常值得一提。旁注:如果真正的函数编写起来很繁重,那么就使用ES6类并将React组件作为类来编写。少一点打字。