React中map函数内onClick绑定报错:Cannot read property 'handleButton' of undefined,同时需实现表格行数据传递至handleButton函数
首先咱们拆解下你遇到的两个核心问题:Cannot read property 'handleButton' of undefined的报错原因,以及如何把当前行的信息传递给handleButton函数。
为什么会出现this.handleButton未定义的错误?
你在this.state.keywords.map()里用了普通匿名函数function(e){...},这种普通函数内部的this指向并不是你的React组件实例(严格模式下会是undefined),所以自然找不到组件上的handleButton方法。
解决方案1:用箭头函数作为map回调(最简洁)
箭头函数会自动继承外层作用域的this(也就是你的组件实例),同时还能轻松把当前行的数据e传递给handleButton:
<tbody> {this.state.keywords.map((e) => { // 改为箭头函数 return ( <tr key={e.row_id}> {/* 务必添加key属性,这是React列表渲染的要求 */} <td>{e.row_id}</td> <td>{e.target_language_keyword}</td> <td>{e.lang}</td> <td><a href={e.url} className="row-link">{e.url.toString().substring(0,40)}</a></td> <td>{e.rank}</td> <td><Button variant="success" onClick={() => this.handleButton(e)} size="lg"> Like</Button></td> </tr> ) })} </tbody>
解决方案2:给map方法传入第二个参数指定this
如果坚持使用普通函数,可以给map的第二个参数传入this,强制让回调函数内部的this指向组件实例:
<tbody> {this.state.keywords.map(function(e){ return ( <tr key={e.row_id}> <td>{e.row_id}</td> <td>{e.target_language_keyword}</td> <td>{e.lang}</td> <td><a href={e.url} className="row-link">{e.url.toString().substring(0,40)}</a></td> <td>{e.rank}</td> <td><Button variant="success" onClick={() => this.handleButton(e)} size="lg"> Like</Button></td> </tr> ) }, this)} {/* 这里传入组件实例的this */} </tbody>
调整handleButton函数接收行数据
现在你可以修改handleButton来使用传递过来的行数据:
handleButton = (rowData) => { console.log("当前点击的行数据:", rowData); // 可以查看行信息 alertify.success("Updated successfully") }
另外补充个小细节:你用了类字段语法定义handleButton = () => {...},这种写法会自动绑定this,所以构造函数里的this.handleButton = this.handleButton.bind(this);其实是多余的,可以删掉啦。
内容的提问来源于stack exchange,提问作者Olgu Dulger
相关产品推荐
相关产品推荐

