为什么JSX道具不应该使用箭头功能或绑定?

JavaScript

Sam蛋蛋Itachi

2020-03-12

我正在用我的React应用程序运行lint,并且收到此错误:

error    JSX props should not use arrow functions        react/jsx-no-bind

这是我运行箭头功能(在里面onClick)的地方:

{this.state.photos.map(tile => (
  <span key={tile.img}>
    <Checkbox
      defaultChecked={tile.checked}
      onCheck={() => this.selectPicture(tile)}
      style={{position: 'absolute', zIndex: 99, padding: 5, backgroundColor: 'rgba(255, 255, 255, 0.72)'}}
    />
    <GridTile
      title={tile.title}
      subtitle={<span>by <b>{tile.author}</b></span>}
      actionIcon={<IconButton onClick={() => this.handleDelete(tile)}><Delete color="white"/></IconButton>}
    >
      <img onClick={() => this.handleOpen(tile.img)} src={tile.img} style={{cursor: 'pointer'}}/>
    </GridTile>
  </span>
))}

是否应避免这种不良做法?最好的方法是什么?

第1131篇《为什么JSX道具不应该使用箭头功能或绑定?》来自Winter(https://github.com/aiyld/aiyld.github.io)的站点

4个回答
NearItachi 2020.03.12

您可以使用react-cached-handler使用箭头功能,而无需担心重新渲染性能:

注意:在内部,它通过指定的键缓存箭头功能,无需担心重新渲染!

render() {

  return <div>
  {
        this.props.photos.map(photo=>
          <Photo key={photo.url}
            onClick={this.handler(photo.url, (url) => { 
                 console.log(url) })}
          />)
   }
 </div>

}

其它功能:

  • 命名处理程序
  • 通过箭头功能处理事件
  • 访问键,自定义参数和原始事件
  • 组件渲染性能
  • 处理程序的自定义上下文
神无阳光 2020.03.12

像这样使用内联函数非常好。起绒规则已过时。

这个规则是从箭头功能不那么普遍并且人们使用.bind(this)的时候开始的。性能问题已在Chrome 49中修复。

请注意不要将内联函数作为道具传递给子组件。

React Router的作者Ryan Florence对此写了一篇很棒的文章:

https://cdb.reacttraining.com/react-inline-functions-and-performance-bdff784f5578

西里猿LEY 2020.03.12

这是因为箭头功能显然会在JSX属性中使用时在每个渲染上创建该功能的新实例。这可能会给垃圾收集器造成巨大压力,也将阻止浏览器优化任何“热路径”,因为函数将被丢弃而不是被重用。

您可以在https://github.com/yannickcr/eslint-plugin-react/blob/master/docs/rules/jsx-no-bind.md中查看整个说明和更多信息。

猴子Sam 2020.03.12

为了避免使用相同的参数创建新函数,您可以记住函数绑定结果,以下是一个简单的实用程序,名为memobindhttps : //github.com/supnate/memobind

问题类别

JavaScript Ckeditor Python Webpack TypeScript Vue.js React.js ExpressJS KoaJS CSS Node.js HTML Django 单元测试 PHP Asp.net jQuery Bootstrap IOS Android