[英]Solution to JSX props not using inline arrow functions?
我最近发现了为什么不应该对组件道具使用嵌入式箭头功能的原因,但是我不知道推荐的解决方案是什么。 这是我使用函数的示例:
renderSectionFooter(isSpecialFooter) {
return (
<SomeFooter
onPress={
isSpecialFooter
? () => this.toggleModalVisibility('specialFooterIsVisible')
: () => this.toggleModalVisibility('boringFooterIsVisible')
}
/>
);
}
这使我拥有一个非常简单干净的切换功能:
toggleModalVisibility(modalIsVisible) { this.setState({ [modalIsVisible]: !this.state[modalIsVisible] }); }
我能看到的唯一方法是为每个“页脚”创建一个特殊的功能,但我认为这与具有类似功能的最佳做法背道而驰。
您不应使用嵌入式箭头功能传递所需的值。 最佳实践是将所需值与函数绑定。 您也可以有条件地绑定值。 这样,您就可以通过两种方式使用单个处理程序处理这两种情况。 考虑下面的代码是否相同:
renderSectionFooter(isSpecialFooter) {
return (
<SomeFooter
onPress={this.toggleModalVisibility.bind(this, isSpecialFooter ? 'specialFooterIsVisible' : 'boringFooterIsVisible')}
/>
);
}
最好的方法是使用在render()
方法之外定义的方法,并在类主体中使用这种方法,这样可以避免内联函数的弊端,并且可以使用箭头函数,而无需绑定函数。 您可以使用以下功能:
_someFunc = (isSpecialFooter) = () => {
if (isSpecialFooter) {
this.toggleModalVisibility('specialFooterIsVisible');
} else {
this.toggleModalVisibility('boringFooterIsVisible')
}
}
renderSectionFooter(isSpecialFooter) {
return (
<SomeFooter
onPress={_someFunc(isSpecialFooter)}
/>
);
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.