[英]Which way is best for conditional rendering in React Native?
When conditionally rendering, would it be better to show and remove via display: none
有条件渲染时,通过
display: none
显示和删除会更好吗
<View style={{display: props.shouldShow ? 'flex':'none'}}>
......
</View>
OR或者
would it be better to call a function like so:像这样调用 function 会更好:
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.返回 null 不会渲染任何东西。
The example you provided where you return the <View></View>
or null
is more idiomatic to react than toggling the style via display
.您提供的返回
<View></View>
或null
的示例比通过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 Rest 您必须查看功能组件
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.