javascript - react 教程 : TypeError: Cannot read property 'props' of undefined

标签 javascript reactjs

我决定学习React并从官方教程开始。一切都很好,直到我的代码达到这种状态:

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

var CommentForm = React.createClass({
  render: () => {
    return (
      <div className="commentForm">
        Hello, world! I am a comment form;
      </div>
    );
  }
});

var Comment = React.createClass({
  rawMarkup: () => {
    var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
    return {__html: rawMarkup};
  },

  render: () => {
    return (
      <div className="comment">
        <h2 className="commentAuthor">
          {this.props.author}
        </h2> // <--- [[[[[[ ERROR IS HERE ]]]]]]
        <span dangerouslySetInnerHtml={this.rawMarkup} />
      </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 yo</Comment>
      </div>
    );
  }
});

ReactDOM.render(
  <CommentBox />,
  document.getElementById('content')
);

当我尝试运行它时,我在 devtools 中收到以下错误:

TypeError: Cannot read property 'props' of undefined

...调试器在标记行处暂停(参见代码)。当我将鼠标悬停在 {this.props.author} 中的 this 时,我可以预览具有 props 属性和所有内容的对象。 .

最佳答案

使用函数声明(render() {}render: function {})而不是箭头函数render: () => {}

var Comment = React.createClass({
  rawMarkup() {
    var rawMarkup = marked(this.props.children.toString(), {sanitize: true});
    return {__html: rawMarkup};
  },

  render() {
    return (
      <div className="comment">
        <h2 className="commentAuthor">
          {this.props.author}
        </h2>
        <span dangerouslySetInnerHtml={this.rawMarkup} />
      </div>
    );
  }
});

Example

An arrow function expression has a shorter syntax compared to function expressions and lexically binds the this value (does not bind its own this, arguments, super, or new.target). Arrow functions are always anonymous.

关于javascript - react 教程 : TypeError: Cannot read property 'props' of undefined,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33957229/

相关文章:

javascript - jQuery 每个 : Pause & Continue iteration after a click

javascript - react 悬停在按钮上会导致另一个按钮悬停在上面

reactjs - React Mocha渲染,DOMException错误文档

javascript - 使用 TypeScript 在 React 中使用 Promise 对象类型数据创建组件

javascript - React useReducer 调度在使用 fetch 请求后不会重新渲染组件

JavaScript 褪色内容

javascript - 检测用户是否连接到互联网?

Javascript 事件和函数触发器

javascript - jQuery 无法在输入中添加类

javascript - 如何将 HTML 页面添加到 React 应用程序