正确的方法将函数传递给React中'哑'组件中的处理程序

时间:2017-07-31 14:36:12

标签: reactjs ecmascript-6 react-redux

看一下这个简单的例子,其中prop toggleData将是一个映射到容器道具的redux thunk动作。

这是将这样的函数传递给子'哑'组件的推荐方法吗?我在网上看到一篇文章说,在处理程序中使用箭头功能是昂贵的,从性能角度来看效率不高。

class Container extends React.Component {
    render(){
        return (
            <Home toggleData={this.props.toggleData}/>
        )
    }
}

const Home = (props) => {
    return (
        <button onClick={()=>{props.toggleData()}}></button>
    )
}

1 个答案:

答案 0 :(得分:5)

是的!避免在JSX中使用箭头函数。由于该函数将在每个渲染上创建,因此可能会导致性能问题。

如果您不需要发送参数,可以执行以下操作:

const Home = (props) => {
    return (
      <button onClick={props.toggleData}></button>
    )
}

如果你需要使用参数,我通常会定义一个类来使用箭头函数创建回调,这样它就会被创建并绑定一次。

class Home extends PureComponent {
  onToggle = () => {
    this.props.toggleData(1, 2, 3);
  }

  render() {
    return (
      <button onClick={this.onToggle}></button>
    )
  }
}
相关问题