首页 文章

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

提问于
浏览
4

看看这个简单的例子,其中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 回答

  • 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>
        )
      }
    }
    

相关问题