简体   繁体   English

使用参数返回未定义来反应onClick函数

[英]React onClick function with Parameter Returning Undefined

When I run the onEditNoteClick function, I am returned an error that says 当我运行onEditNoteClick函数时,返回的错误提示

  Cannot read property 'onEditNoteClick' of undefined

I'm not sure why I'm getting this issue. 我不确定为什么会遇到这个问题。 To make it simpler, I set the onEditNoteClick parameter to 1 but it still doesn't work. 为了简化起见,我将onEditNoteClick参数设置为1,但仍然不起作用。

  constructor(props) {
      super(props);
      this.onEditNoteClick = this.onEditNoteClick.bind(this);
  }

  ......

  onEditNoteClick(id){
    console.log("came to this function");
  }

  renderNotes(note) {
    return (
      <tr key={note.id}>
          <td> {note.name}</td>
          <td> {note.description} </td>
          <td className="edit" onClick={this.onEditNoteClick.bind(this,1)}><i className="fa fa-fw fa-pencil fa-lg"></i> </td>
      </tr>
    );
  }

.....

render(){
   {this.props.notes.map(this.renderNotes)}

I think I need to add a bind method with the notes map, something like this: 我想我需要在注释地图中添加一个bind方法,如下所示:

   {this.props.notes.map(this.renderNotes).bind(this)}

But I'm not sure what the correct syntax is. 但是我不确定正确的语法是什么。

I think I need to add a bind method with the notes map, something like this: 我想我需要在注释地图中添加一个bind方法,如下所示:

 {this.props.notes.map(this.renderNotes).bind(this)} 

That would be incorrect. 那是不正确的。 .bind can only be called on a function , but .map returns an array , not a function. .bind只能在函数调用 ,但是.map返回一个数组 ,而不是函数。 What you have to is set the this value of the this.renderNotes method. 您所需要的是设置this.renderNotes方法的this值。 The easiest way to achieve this would be to pass this as second argument to .map (see the documentation ): 实现这一目标的最简单的方法是通过this作为第二个参数.map (见文档 ):

{this.props.notes.map(this.renderNotes, this)}

Alternatively, bind this.renderNotes in the constructor just like you do with the other method: 或者,就像使用其他方法一样,将this.renderNotes绑定到constructor

this.renderNotes = this.renderNotes.bind(this);

and then you can omit the second argument: 然后可以省略第二个参数:

{this.props.notes.map(this.renderNotes)}

See also: How to access the correct `this` context inside a callback? 另请参见: 如何在回调内访问正确的`this`上下文?

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM