繁体   English   中英

哪种方式最适合 React Native 中的条件渲染?

[英]Which way is best for conditional rendering in React Native?

有条件渲染时,通过display: none显示和删除会更好吗

<View style={{display: props.shouldShow ? 'flex':'none'}}>
     ......
</View>

或者

像这样调用 function 会更好:


const showComponent = (props) => {
    if (props.shouldShow)
    {
        return (<View> ... </View)

    }
    else
    {
        return
    }

}
...
...
const Thingy = (props) => {
    return(
        <View>
            showComponent(props)
        </View>
    )
}

根据我所看到的个人经验和反应项目,有条件地渲染组件的一种有效/可信的方法是

const showComponent = props.shouldShow ? (<View>...</View>) : null

return(
   <div>
      {showComponent}
   </div>

如果是显示或不显示的问题,我通常会使用三元表达式。

render(){
  let display = ( ...some expression )
  return(
    display ? <View>Hello</View > : null
  );
}

返回 null 不会渲染任何东西。

您提供的返回<View></View>null的示例比通过display切换样式更习惯于做出反应。

如果您使用的是功能组件,那么最新的方法会更容易,因为,

return (
<View style={Condition ? Styles.A : Styles.B}>

</View>

)
const Styles = StyleSheet.create({ A: { display:"none" }, B:{ display:"flex" } } )

Rest 您必须查看功能组件

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM