问题
In my React Native app, I'm trying to conditionally render a <Text>
component based on whether or not a particular string exists. I tried to do it this way:
<View>
{
someString
&&
<Text>
{someString}
</Text>
}
</View>
This threw the error Text strings must be rendered within a <Text> component
. I did it this way and it worked fine.
<View>
{
someString
?
<Text>
{someString}
</Text>
:
null
}
</View>
I assume the problem is that with the first method, it's trying to actually render the string, rather than checking for its existence. I'd like to use the first method though, since it's cleaner and I've used the same convention elsewhere in my code.
Does anyone know if it's possible to use &&
like this instead of ?
+:
?
回答1:
It's because an empty
string is false-y meaning it will be rendered in the component. You can't render a string (even an empty one like ''
) without wrapping it in a Text component.
https://www.freecodecamp.org/news/conditional-rendering-in-react-using-ternaries-and-logical-and-7807f53b6935/
Empty string values suffer the same issue as numbers. But because a rendered empty string is invisible, it’s not a problem that you will likely have to deal with, or will even notice. However, if you are a perfectionist and don’t want an empty string on your DOM, you should take similar precautions as we did for numbers above.
来源:https://stackoverflow.com/questions/61391813/react-native-can-you-conditionally-render-jsx-based-on-the-existence-of-a-strin