React.js TypeError this.props未定义

时间:2017-06-20 10:05:06

标签: javascript reactjs

我开始尝试学习反应并遇到了一个我无法理解的问题。通过一个教程制作一个简单的注释编辑Web应用程序,当我尝试更新注释时,我收到此错误" TypeError:_this3未定义",特别是在这些行上:

this.props.updateCommentText(this.refs.newText.value, this.props.index);

和这一个:

updateCommentText={()=>this.updateComment} 

以下是完整的JavaScript代码:

class Comment extends React.Component{

  constructor(){
    super();
    this.state = {
      editing: false,
    };

    this.edit = this.edit.bind(this);
    this.save = this.save.bind(this);
  }

  edit(){
    this.setState({
      editing: true,
    });
  }

  save(){
    this.props.updateCommentText(this.refs.newText.value, this.props.index);
    this.setState({
      editing: false,
    });
  }
  remove(){
    console.log('Removing comment');
    this.props.deleteFromBoard(this.props.index)
  }

  renderNormal(){
    return (
        <div className="commentContainer">
          <div className="commentText">{this.props.children}</div>
          <button onClick={this.edit} className="button-primary">Edit</button>
          <button onClick={this.remove} className="button-danger">Remove</button>
        </div>

      );
  }

  renderForm(){
    return (
        <div className="commentContainer">
          <textarea ref="newText" defaultValue={this.props.children}></textarea>
          <button onClick={this.save} className="button-success">Save</button>
        </div>

      );
  }

  render(){
    if(this.state.editing){

      return this.renderForm();

    } else {

      return this.renderNormal();

    }
  }
}

class Board extends React.Component{

  constructor(){
    super();
    this.state = {
      comments: [
        "Hiya",
        "Awk well",
        "Boo-urns"
      ],
    }
  }

  removeComment(i){
    console.log("Removing comment: " + i);
    var arr = this.state.comments;
    arr.splice(i, 1);
    this.setState({
      comments: arr
    });
  }

  updateComment(newText, i){
    console.log("Updating comment: " + i);
    var arr = this.state.comments;
    arr[i] = newText;
    this.setState({
      comments: arr,
    });

  }

  eachComment(text, i){
    return (
      <Comment key={i} index={i} 
      updateCommentText={()=>this.updateComment} 
      deleteFromBoard={()=>this.removeComment}>

        {text}

      </Comment>
    );
  }

  render(){
    return (
        <div className="board">
          {
            this.state.comments.map(this.eachComment)
          }
        </div>

    );
  }
}



// ========================================

ReactDOM.render(
  <Board />,
  document.getElementById('container')
);

我假设某些事情超出了范围,但我不知道在哪里。

1 个答案:

答案 0 :(得分:1)

这是一个问题,但可能还有更多:)

在此代码中:

updateCommentText={()=>this.updateComment}

你的箭头函数返回一个函数引用,但是在调用updateCommentText调用函数。

请改为尝试:

updateCommentText={(value, index)=>this.updateComment(value, index)}
顺便说一下,你有类似的问题:

deleteFromBoard={()=>this.removeComment}