看看这个简单的示例,其中 prop toggleData
将是映射到容器 props 的 redux thunk 操作。
这是将这样的函数传递给子“哑”组件的推荐方法吗?我在网上读到一篇文章说,从性能角度来看,在处理程序中使用箭头函数非常昂贵,而且效率不高。
class Container extends React.Component {
render(){
return (
<Home toggleData={this.props.toggleData}/>
)
}
}
const Home = (props) => {
return (
<button onClick={()=>{props.toggleData()}}></button>
)
}
最佳答案
是的!避免在 JSX 中使用箭头函数。由于该函数将在每次渲染时创建,因此这可能会导致稍后出现性能问题。
如果你不需要发送参数,你可以这样做:
const Home = (props) => {
return (
<button onClick={props.toggleData}></button>
)
}
如果您需要使用参数,我通常定义一个类来使用箭头函数创建回调,这样它只被创建和绑定(bind)一次。
class Home extends PureComponent {
onToggle = () => {
this.props.toggleData(1, 2, 3);
}
render() {
return (
<button onClick={this.onToggle}></button>
)
}
}
关于reactjs - 在 React 中将函数传递给 'dumb' 组件中的处理程序的正确方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45418799/