Reactjs react native中条件呈现的最佳实践
我想要一些关于在react native中有条件地呈现元素或组件时的最佳实践的建议。我的问题是,当条件为非真时,最好返回null还是只运行if条件?我知道,如果返回null,那么生命周期方法仍在运行,但我关心的是,如果我不返回任何内容,是否会产生影响或性能差异 例一Reactjs react native中条件呈现的最佳实践,reactjs,react-native,Reactjs,React Native,我想要一些关于在react native中有条件地呈现元素或组件时的最佳实践的建议。我的问题是,当条件为非真时,最好返回null还是只运行if条件?我知道,如果返回null,那么生命周期方法仍在运行,但我关心的是,如果我不返回任何内容,是否会产生影响或性能差异 例一 renderText(name) { if(name === 'Abba') { return <Text>{name}</Text> } } renderText(名称){ 如果(名称==
renderText(name) {
if(name === 'Abba') {
return <Text>{name}</Text>
}
}
renderText(名称){
如果(名称=='Abba'){
返回{name}
}
}
例二
renderText(name) {
if(name === 'Abba') {
return <Text>{name}</Text>
} else {
return null
}
}
renderText(名称){
如果(名称=='Abba'){
返回{name}
}否则{
返回空
}
}
我认为这样的条件渲染可能更好
renderText(name) {
return (
{ name === 'Abby' &&
<Text>
{name}
</Text>
}
)
}
renderText(名称){
返回(
{name==='Abby'&&
{name}
}
)
}
对于最顶层的元素,最好返回一些JSX或null
,即返回name=='Abba'?{name}:null
。如果它位于某个JSX内部,则可以使用&&
操作符,即name==='Abba'&&&
。