背景

上周玩了两天 React,用 React + antd + Table 实现一个简单的列表功能,列表组件渲染时,this 对象跟当前组件定义不是同一个,导致定位不到对应的操作事件。

columns

const columns = [{
    title: '简介',
    width: '20%',
    dataIndex: 'remark',
}, {
    title: '操作',
    width: '25%',
    dataIndex: 'id',
    // 操作列跳转,且传递 ID 参数
    render:(text,record) =>(
<div>
  <Link style={btnStyle} to={"/toDetail/"+record.id}><Button size='small' type="default">详情</Button></Link>
  <Link style={btnStyle} to={"/toEdit/"+record.id}><Button size='small' type="primary">编辑</Button></Link>
  <Button style={btnStyle} onClick={()=>{this.remove(record)}} size='small' type="danger">删除</Button>
</div>
)
}]

属性的方式,但是个函数,也没问题,this. 能拿到对应的方法。

render:(text,record)=> {
  return (
      <div>
          <Link style={btnStyle} to={"/toDetail/"+record.id}><Button size='small' type="default">详情</Button></Link>
          <Link style={btnStyle} to={"/toEdit/"+record.id}><Button size='small' type="primary">编辑</Button></Link>
          <Button style={btnStyle} onClick={()=>{this.remove(record)}} size='small' type="danger">删除</Button>
      </div>
  )
}

有问题的方法

另一种方式直接写函数的做法,指针指向不明,无法定位到对应的方法。

{
 title: '操作',
 width: '25%',
 dataIndex: 'id',
 // 操作列跳转,且传递 ID 参数
 render(text,record) {
     return (
         <div>
             <Link style={btnStyle} to={"/toDetail/"+record.id}><Button size='small' type="default">详情</Button></Link>
             <Link style={btnStyle} to={"/toEdit/"+record.id}><Button size='small' type="primary">编辑</Button></Link>
             <Button style={btnStyle} onClick={()=>{this.remove(record)}} size='small' type="danger">删除</Button>
         </div>
     )
 }
}

这段代码就报错:
在这里插入图片描述
这个是从 GitHub 上的一个项目中拷贝的代码,简单跳转没问题,但是有需要调用其他方法的时候就过不去。

为什么呢?

属性 render:(text,record)=> {} 和直接提供一个函数 render(text,record) 的区别是什么,为何差距这么大呢?

看官方示例都是第一种,render: 函数

2021 年 12 月 22 日补充解释,区别是匿名函数的编写过程中,React 会自动完成 this 对象的绑定操作,而非匿名函数则需要自己绑定。

这是笔者遇到使用具名函数时,按钮点击事件提前被触发后学到的知识点,联想之前的编码经历,突然就理解了本文遇到的问题了。

Logo

为开发者提供学习成长、分享交流、生态实践、资源工具等服务,帮助开发者快速成长。

更多推荐