gpt4 book ai didi

javascript - 在 React 中写 Event 哪种方法更优雅?

转载 作者:行者123 更新时间:2023-11-29 23:19:38 25 4
gpt4 key购买 nike

写代码的时候总想找到更优雅的方式。更好的可读性和更高的效率。您更喜欢哪种方法?或者你有其他更好的方法。

方法一

在我看来,这是一个丑陋的方法,混合代码。

class Layer extends Component {
render(){
return (
<li
onClick={(event)=>{
console.log(event.target, this.props.layerId);
// Some Code
}}
>
{layerName}
</li>
)
}
}

方法二

常用方法。但是每次点击都会创建一个匿名函数。效率?

class Layer extends Component {
onLayerClick(event){
console.log(event.target, this.props.layerId);
// Some Code
}

render(){
return (
<li
onClick={(event)=>{
this.onLayerClick(event);
}}
>
{layerName}
</li>
)
}
}

方法三

我最喜欢的方法。但是需要绑定(bind)。

class Layer extends Component {
onLayerClick(event){
console.log(event.target, this.props.layerId);
// Some Code
}

render(){
return (
<li
onClick={this.onLayerClick.bind(this)}
>
{layerName}
</li>
)
}
}

最佳答案

非常有意见并且基于上下文,但是属性初始化的箭头函数使它成为可能,因此您不必在渲染方法或构造函数中绑定(bind)

class Layer extends Component {
onLayerClick = (event) => {
console.log(event.target, this.props.layerId);
};

render(){
return <li onClick={this.onLayerClick}>{layerName}</li>;
}
}

然而,class properties还没有在语言中,所以不是所有的开发环境都可以访问它们。在我看来,第二个最佳选择是 bind 构造函数中的方法。比class properties选项要多写一点,但是不需要每次都在render方法中新建一个函数。

class Layer extends Component {
constructor(props) {
super(props);
this.onLayerClick = this.onLayerClick.bind(this);
}

onLayerClick(event) {
console.log(event.target, this.props.layerId);
};

render(){
return <li onClick={this.onLayerClick}>{layerName}</li>;
}
}

关于javascript - 在 React 中写 Event 哪种方法更优雅?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51197955/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com