React - 传递没有值的 prop

boy*_*ygs 5 reactjs react-native native-base

我正在使用NativeBaseReact Native

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

    <Button warning>
        <Text>Hello</Text>
    </Button>
Run Code Online (Sandbox Code Playgroud)

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

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

<Button {this.props.type}>
    <Text>Hello</Text>
</Button>
Run Code Online (Sandbox Code Playgroud)

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

是否可以传递没有值的 props?

zhu*_*ber 7

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

这两个是相等的:

<Button primary />
<Button primary={true} />
Run Code Online (Sandbox Code Playgroud)

考虑到上述情况,您可以使用扩展属性语法:

<Button {...{ [this.props.type]: true }}>
    <Text>Hello</Text>
</Button>
Run Code Online (Sandbox Code Playgroud)

编辑(详细解释):

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

<Button {...{ success: true }}>
Run Code Online (Sandbox Code Playgroud)

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

<Button success={true} >
Run Code Online (Sandbox Code Playgroud)

正如我已经提到的,请看一下这个解释