0

正在关注他们网站上的 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")
);

但是,如果我在第一个组件注释中使用箭头符号,即:

(*参数*) => {}

而不是普通的函数声明符号,即:

函数(*参数*){}

chrome解释器会吐出以下错误:

未捕获的类型错误:无法读取未定义的属性“道具”


任何人都可以对此事有所了解吗?

4

1 回答 1

4

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

所以, forrender和其他属于你的组件并且需要访问组件 as 的方法this,你需要使用真正的函数。不过,您可以将箭头函数用于嵌套函数(在那里使用它们更有意义)。

于 2015-11-26T17:39:28.090 回答