close
問題: 如何在RN內的return中,寫if else判斷?
hope you are doing well.
I am stuck in little problem is i want to pass a tag only if my condition goes true.
for ex:
render(
return(
<View>
{
if(data==='test')
{
<Text>Hello this is Test Execution </Text>
}
}
</View>
)
)
i want to do exactly like above example.
i get some errors i can't understand what to do so please help me.
Thank you
--
答: 把if else判斷搬出來另外寫一個function來判斷是比較好的方式。
you need to write a function which optionally renders your text.
renderText(data) {
if (data === 'test') {
return <Text>Hello this is Test Execution </Text>;
}
}
render() {
return(
<View>
{this.renderText(data)}
</View>
);
}
--
比較簡單但是後續難維護的方式:改為使用 ? : 運算子去判斷
A short and safe way would be to use a ternary operator and render null
if false:
{ data === 'test' ? <Text>Hello this is Test Execution </Text> : null }
--
轉自 https://stackoverflow.com/questions/47260391/how-to-write-if-else-under-return-react-native
全站熱搜
留言列表