我读了一堆关于冠词() => {}
语法,在构造函数结合,在props等结合。但是从我的理解,结合this
是昂贵的性能代价,做自动带箭头的功能结合是昂贵的,因为它每次都会创建一个新的匿名函数。
那么处理这个问题的最高效的“react方式”是什么?
构造函数中的绑定似乎适用于不需要传递参数的函数,如下所示:
constructor(props) {
super(props)
this.handleClick = this.handleClick.bind(this)
}
但是我们如何处理传递参数的绑定函数,而不是在 prop 中绑定它,像这样:
<li onClick={this.handleClick.bind(this, item.id)} />{item.name}</li>
是否结合this
的构造函数,然后结合null
或undefined
在绑定功能,只有结合曾经在props结果?
请随时纠正我的任何误解。似乎这个问题的解决方案应该更广为人知和普遍......如果我不只是生活在岩石下!
编辑:
即使有抽象,点击处理程序也不会与每个单独的项目渲染绑定吗?
在这里的文章中,他们给出了这个例子来避免绑定点击处理程序,但是因为 React.createClass 会自动绑定方法,我看不出这实际上是如何在每个项目渲染上绑定的?
var List = React.createClass({
render() {
let { handleClick } = this.props;
// handleClick still expects an id, but we don't need to worry
// about that here. Just pass the function itself and ListItem
// will call it with the id.
return (
<ul>
{this.props.items.map(item =>
<ListItem key={item.id} item={item} onItemClick={handleClick} />
)}
</ul>
);
}
});
var ListItem = React.createClass({
render() {
// Don't need a bind here, since it's just calling
// our own click handler
return (
<li onClick={this.handleClick}>
{this.props.item.name}
</li>
);
},
handleClick() {
// Our click handler knows the item's id, so it
// can just pass it along.
this.props.onItemClick(this.props.item.id);
}
});
有人可以解释一下吗?这不是看起来像它避免了绑定每个 ListItem 渲染,但由于 React.createClass 中的自动绑定,它仍然可以吗?
我用class List extends Component
语法而不是 createClass尝试了这个例子,this.handleClick
但没有定义,因为 handleClick 方法没有绑定到类。
归根结底,这似乎只是清理了冗长,实际上并没有通过减少方法绑定来提高性能......