简体   繁体   English

React Native:你能根据字符串的存在有条件地渲染 JSX 吗?

[英]React Native: Can you conditionally render JSX based on the existence of a string?

In my React Native app, I'm trying to conditionally render a <Text> component based on whether or not a particular string exists.在我的 React Native 应用程序中,我试图根据特定字符串是否存在有条件地呈现<Text>组件。 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 .这引发了错误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 ?有谁知道是否可以像这样使用&&而不是? + : ? + :

It's because an empty string is false-y meaning it will be rendered in the component.这是因为empty字符串是 false-y 意味着它将在组件中呈现。 You can't render a string (even an empty one like '' ) without wrapping it in a Text component.如果不将字符串包装在 Text 组件中,则无法呈现字符串(即使是像''这样的空字符串)。

https://www.freecodecamp.org/news/conditional-rendering-in-react-using-ternaries-and-logical-and-7807f53b6935/ 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.但是,如果您是一个完美主义者并且不希望 DOM 中出现空字符串,您应该采取与我们在上面对数字所做的类似的预防措施。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM