React Native:你能根据字符串的存在有条件地渲染 JSX 吗?
React Native: Can you conditionally render JSX based on the existence of a string?
在我的 React Native 应用程序中,我尝试根据特定字符串是否存在有条件地呈现 <Text>
组件。我试过这样做:
<View>
{
someString
&&
<Text>
{someString}
</Text>
}
</View>
这引发了错误 Text strings must be rendered within a <Text> component
。我这样做了,效果很好。
<View>
{
someString
?
<Text>
{someString}
</Text>
:
null
}
</View>
我认为问题在于第一种方法试图实际呈现字符串,而不是检查它是否存在。不过,我想使用第一种方法,因为它更简洁,而且我在代码的其他地方使用了相同的约定。
有谁知道是否可以像这样使用 &&
而不是 ?
+:
?
这是因为 empty
字符串是 false-y 意味着它将在组件中呈现。如果不将字符串包装在文本组件中,则无法呈现字符串(即使是 ''
这样的空字符串)。
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.
在我的 React Native 应用程序中,我尝试根据特定字符串是否存在有条件地呈现 <Text>
组件。我试过这样做:
<View>
{
someString
&&
<Text>
{someString}
</Text>
}
</View>
这引发了错误 Text strings must be rendered within a <Text> component
。我这样做了,效果很好。
<View>
{
someString
?
<Text>
{someString}
</Text>
:
null
}
</View>
我认为问题在于第一种方法试图实际呈现字符串,而不是检查它是否存在。不过,我想使用第一种方法,因为它更简洁,而且我在代码的其他地方使用了相同的约定。
有谁知道是否可以像这样使用 &&
而不是 ?
+:
?
这是因为 empty
字符串是 false-y 意味着它将在组件中呈现。如果不将字符串包装在文本组件中,则无法呈现字符串(即使是 ''
这样的空字符串)。
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.