[英]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.