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

Sam*_*uel 4 ecmascript-6 reactjs 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>
    )
}
Run Code Online (Sandbox Code Playgroud)

Cry*_*fel 6

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

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

const Home = (props) => {
    return (
      <button onClick={props.toggleData}></button>
    )
}
Run Code Online (Sandbox Code Playgroud)

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

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

  render() {
    return (
      <button onClick={this.onToggle}></button>
    )
  }
}
Run Code Online (Sandbox Code Playgroud)

  • 上面的注释不正确 - 如果你在该类上下文中执行`onToggle =()=>`(即作为类属性),则不需要绑定函数. (3认同)