使用地图时无法读取未定义的属性“handleClick" [英] Cannot read property 'handleClick' of undefined when using map

查看:56
本文介绍了使用地图时无法读取未定义的属性“handleClick"的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 react-router 制作一个类似于 Link 的表格行功能.

I am trying to make a table row function like a Link with react-router.

我不断收到错误无法读取未定义的属性handleClick"

handleClick(user) {
   this.router.transitionTo('index', user);
}

render(){
   var userNodes = this.props.posts.map(function(user, i){
       return (
         <tr onClick={() => this.handleClick(user)}>
           <Td>{user.postId}</Td>
           <Td>{user.title}</Td>
           <Td>{user.body}</Td>   
         </tr>
       )
   });
...

推荐答案

使用箭头函数作为 map 回调来保留组件上下文(否则回调内的 this 将不会指向到组件实例):

Use arrow function as map callback to preserve component context (otherwise this inside the callback will not point to the component instance):

render(){
   var userNodes = this.props.posts.map((user, i) => {
       return (
         <tr onClick={() => this.handleClick(user)}>
           <Td>{user.postId}</Td>
           <Td>{user.title}</Td>
           <Td>{user.body}</Td>   
         </tr>
       )
   });

这篇关于使用地图时无法读取未定义的属性“handleClick"的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆