React - 传递没有价值的道具

React - Pass prop without a value

我正在使用 NativeBaseReact Native

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

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

您可以使用不同的类型,例如 infosuccess,而不是 warning

现在,我想基于道具创建这些按钮并尝试做这样的事情:

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

但是我找不到方法,因为这个 prop 没有值。

是否可以传递没有值的道具?

可以无值传递的组件 props 基本上是 boolean props 并被解析为 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