未捕获的 ReferenceError:未定义 handleClick - React

新手上路,请多包涵

我将开门见山。这是我在 ReactJS 应用程序中的组件:

 class BooksList extends Component {

  constructor(props) {
    super(props);
    this.handleClick = this.handleClick.bind(this);

  }

  handleClick() {
    e.preventDefault();
    console.log("The link was clicked");
  }

  render() {
    return (
      <div>
        <a className="btn btn-success" onClick={handleClick}>
            Add to cart
        </a>
      </div>
    );
  }
}

为什么加载组件时会出现以下错误?

 Uncaught ReferenceError: handleClick is not defined

编辑:

在您回答后,我将代码更改为:

   handleClick(e) {
    e.preventDefault();
    console.log("Item added to the cart");
  }

  renderBooks(){
      return this.props.myBooks.data.map(function(book){
          return (
                  <div className="row">
                    <table className="table-responsive">
                      <tbody>
                        <tr>
                          <td>
                            <p className="bookTitle">{book.title}</p>
                          </td>
                        </tr>
                        <tr>
                          <td>
                             <button value={book._id} onClick={this.handleClick}>Add to cart</button>
                          </td>
                        </tr>
                      </tbody>
                    </table>
                  </div>
          );
      });
    }
  }

render() {
    return (
      <div>
        <div>
          <h3>Buy our books</h3>
              {this.renderBooks()}
        </div>
      </div>
    );
  }

如您所见,我有 .map 遍历书籍列表。对于每本书,我都有一个按钮,如果单击该按钮,会将特定的书添加到用户的购物车中。

如果我按照@Tharaka Wijebandara 的回答,我可以让按钮在外面工作 .map 但在这种情况下我仍然会收到错误消息:

 Uncaught (in promise) TypeError: Cannot read property 'handleClick' of undefined
    at http://localhost:8080/bundle.js:41331:89
    at Array.map (native)

原文由 splunk 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 524
2 个回答

您在编辑部分提到的问题的解决方案。

Reason is, you are loosing the context in map callback function, you need to bind this (class context) with callback function or Use arrow function ,它会解决你的问题。

通过使用 箭头功能

 renderBooks(){
      return this.props.myBooks.data.map((book) => { //here
          return (
                  .....
          );
      });
  }

或者将 .bind(this) 与回调函数一起使用,如下所示:

 renderBooks(){
      return this.props.myBooks.data.map(function (book) {
          return (
                  .....
          );
      }.bind(this));    //here
 }

原文由 Mayank Shukla 发布,翻译遵循 CC BY-SA 3.0 许可协议

使用 this.handleClick

 <a className="btn btn-success" onClick={this.handleClick}>
  Add to cart
</a>

并且您忘记在 handleClick 方法中添加 e 作为参数。

 handleClick(e) {
  e.preventDefault();
  console.log("The link was clicked");
}

原文由 Tharaka Wijebandara 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题