Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/reactjs/24.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/0/react-native/7.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Reactjs react native中条件呈现的最佳实践_Reactjs_React Native - Fatal编程技术网

Reactjs react native中条件呈现的最佳实践

Reactjs react native中条件呈现的最佳实践,reactjs,react-native,Reactjs,React Native,我想要一些关于在react native中有条件地呈现元素或组件时的最佳实践的建议。我的问题是,当条件为非真时,最好返回null还是只运行if条件?我知道,如果返回null,那么生命周期方法仍在运行,但我关心的是,如果我不返回任何内容,是否会产生影响或性能差异 例一 renderText(name) { if(name === 'Abba') { return <Text>{name}</Text> } } renderText(名称){ 如果(名称==

我想要一些关于在react native中有条件地呈现元素或组件时的最佳实践的建议。我的问题是,当条件为非真时,最好返回null还是只运行if条件?我知道,如果返回null,那么生命周期方法仍在运行,但我关心的是,如果我不返回任何内容,是否会产生影响或性能差异

例一

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'&&&