簡體   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