未捕获的引用错误:handleClick未定义 - React

4

我来直入主题。这是我在 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)
3个回答

6

使用 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");
}

4

您提到的问题的解决方案如下。

原因是,您在map回调函数中失去了context,您需要使用bind将此(类上下文)与回调函数绑定或使用箭头函数,这将解决您的问题。

通过使用箭头函数

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
 }

0

在 @Tharaka Wijebandara 的答案中,你还可以用以下方式将函数声明为 const

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

其中handleClick被定义为:

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

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接