javascript - Which way is best for conditional rendering in React Native? - Stack Overflow

When conditionally rendering, would it be better to show and remove via display: none<View style={{d

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>
    )
}

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>
    )
}
Share Improve this question asked Nov 19, 2019 at 20:02 Jake ChambersJake Chambers 5632 gold badges8 silver badges25 bronze badges 1
  • Do you mean better in performance? – Jose Rojas Commented Nov 19, 2019 at 20:11
Add a ment  | 

4 Answers 4

Reset to default 2

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

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.

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

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

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

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 ponent

发布者:admin,转转请注明出处:http://www.yc00.com/questions/1744752571a4591686.html

相关推荐

发表回复

评论列表(0条)

  • 暂无评论

联系我们

400-800-8888

在线咨询: QQ交谈

邮件:admin@example.com

工作时间:周一至周五,9:30-18:30,节假日休息

关注微信