reactjs - React - 传递没有值的 prop

标签 reactjs react-native native-base

我将 NativeBaseReact Native 一起使用。

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

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

您可以使用不同的类型来代替警告,例如信息成功

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

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

但是我找不到方法来做到这一点,因为这个 Prop 没有值。

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

最佳答案

可以无值传递的组件属性基本上是 boolean 属性,并解析为 true

这两个是相等的:

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

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

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

编辑(详细说明):

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

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

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

<Button success={true} >

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

关于reactjs - React - 传递没有值的 prop,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57832302/

相关文章:

javascript - 将输入中的值添加为 ReactJS 中的新表行

html - 自定义 CSS 下拉菜单以专注于下拉元素

ios - 迁移到 firebase v6 后找不到 RNFirebaseNotifications.h。 react native

react-native - 根据一个参数修改header

react-native - react 导航 : stack navigator with tab navigator is not working

javascript - 使用 setState 响应计算密集型函数的更新进度

javascript - 如何使用 firestore orderBy 但同时添加未定义的值

android - 导航器已弃用并已从此包中删除 (expo)

javascript - signinwithphonenumber 身份验证失败

react-native - 文本复制后如何向用户显示 "text is copied"?