简体   繁体   中英

Which way is best for conditional rendering in React Native?

When conditionally rendering, would it be better to show and remove via display: none

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

OR

would it be better to call a function like so:


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

    }
    else
    {
        return
    }

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

From personal experience and react projects i have seen, An efficient / trusted way to conditionally render a component is

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

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

If it's a matter of display or no display I usually fall back to ternary expressions.

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

Returning null will not render anything.

The example you provided where you return the <View></View> or null is more idiomatic to react than toggling the style via display .

If you are Using Functional Component, The latest Approach then its much more easy as,

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

</View>

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

Rest you have to look into functional component

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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