【问题标题】:React - Pass prop without a valueReact - 传递没有值的道具
【发布时间】:2020-01-09 22:32:28
【问题描述】:

我正在使用 NativeBaseReact Native

以这种方式创建的 NativeBase 按钮​​:

    <Button warning>
        <Text>Hello</Text>
    </Button>

您可以使用不同的类型来代替 warning,例如 infosuccess

现在,我想根据道具创建这些按钮并尝试执行以下操作:

<Button {this.props.type}>
    <Text>Hello</Text>
</Button>

但我找不到办法,因为这个道具没有价值。

可以不带值传递props吗?

【问题讨论】:

  • &lt;Button {...this.props}&gt; 可以帮助你,如果你可以解构 props 对象,即使 props 是空对象也可以正常工作
  • 这个answer 可能会有所帮助

标签: reactjs react-native native-base


【解决方案1】:

可以无值传递的组件props基本都是booleanprops,解析为true

这两个是相等的:

<Button primary />
<Button primary={true} />

考虑到上述情况,您可以使用spread attribute 语法:

<Button {...{ [this.props.type]: true }}>
    <Text>Hello</Text>
</Button>

EDIT(详细解释):

假设您的 this.props.type 是“成功”,Button 元素将解决此问题(因为使用了动态属性名称):

<Button {...{ success: true }}>

现在,当您破坏对象(这三个点)时,您将获得其所有属性和相应的值作为元素的道具:

<Button success={true} >

正如我已经提到的,请查看this explanation

【讨论】:

  • 谢谢,它有效。你能解释一下它为什么有效吗?我不确定我是否完全理解这一点。
猜你喜欢
  • 2019-06-09
  • 1970-01-01
  • 2018-11-20
  • 2020-02-18
  • 1970-01-01
  • 2018-05-22
  • 2020-11-17
  • 2020-06-12
  • 1970-01-01
相关资源
最近更新 更多