React Native:您可以根据字符串的存在条件有条件地渲染JSX吗? [英] React Native: Can you conditionally render JSX based on the existence of a string?

查看:296
本文介绍了React Native:您可以根据字符串的存在条件有条件地渲染JSX吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的React Native应用程序中,我试图根据是否存在特定字符串有条件地呈现< Text> 组件。我尝试通过这种方式进行操作:

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>

这引发了错误文本字符串必须在< Text>中显示。组件

<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 ?+:?

推荐答案

这是因为 empty 字符串为false-y意味着它将在组件中呈现。如果不将字符串包装在Text组件中,就无法呈现字符串(甚至是像''这样的空字符串)。

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/


空字符串值遇到与数字相同的问题。但是,由于渲染的空字符串是不可见的,因此这不是您可能不得不处理甚至不会注意到的问题。但是,如果您是完美主义者,并且不想在DOM上使用空字符串,则应采取与上述数字类似的预防措施。

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:您可以根据字符串的存在条件有条件地渲染JSX吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆