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

旧时模样 提交于 2020-05-17 07:42:45

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!