【问题标题】:Problem with conditional rendering in React Native using falsey value在 React Native 中使用错误值进行条件渲染的问题
【发布时间】:2018-09-05 02:17:16
【问题描述】:
<Item stackedLabel disabled>
  <Label style={{ color: 'black' }}>{someLabel}</Label>
    {
      0 &&
      <Input style={{ color: 'grey' }} value={this.props.someprop} disabled />
    }
</Item>

我创建了一个snack,用于演示我们可以使用假值进行条件渲染。但是,上面的代码给我报错了

Invariant Violation:文本字符串必须在组件内呈现

但是,如果我们将 0 替换为 null/false 那么它工作正常吗?

【问题讨论】:

    标签: reactjs react-native native-base


    【解决方案1】:

    我创建了一个零食,用于演示我们可以使用虚假值 条件渲染。

    而零食失败了,所以实际上并非如此。

    扩展 Saeed 的答案,代码 sn-p 相当于

    <Item stackedLabel disabled>
      <Label style={{ color: 'black' }}>{someLabel}</Label>
      0
    </Item>
    

    React Native 不知道如何处理零,因此会打印错误。

    【讨论】:

    • 我不明白?零食的哪一部分失败了?
    • 运行模拟器时,由于0 而看不到Change code in the editor and watch it change on your phone! Save to get a shareable url.,这显然是意料之中的
    • @Isaac 在 android 上运行零食,你会看到一个错误
    • hmmm 看起来确实如此。谢谢你告诉我!
    【解决方案2】:

    这是因为 React 将 0 视为字符串。

    用这个技巧简单地将其转换为布尔值:

    !!(任何非布尔值)

    // this is equal to false
    !!(0)
    

    【讨论】:

    • 并非如此,这就是为什么我创建了snack 来演示React 正确地将0 处理为错误值。但是我不能确定这是 NativeBase 的问题
    • 在 ReactJS(非本机)上,它将 0 作为字符串处理。所以它假设它是一个字符串
    猜你喜欢
    • 2021-08-21
    • 2019-08-18
    • 2021-10-31
    • 1970-01-01
    • 2020-12-28
    • 2019-03-01
    • 2020-01-15
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多