reactjs - 是否可以使用展开运算符来设置 react 组件 Prop ?

标签 reactjs react-props react-component

我想使用扩展运算符来设置组件 Prop 。这主要是因为我不想为每个 props 值使用 state。这可能吗?下面的代码返回一个错误,指出 Prop 丢失。提前致谢!

const compProps = { 
    label: 'Test Label',
    value: 'Test Value',
    icon: 'test-icon'
}

<CustomComp {...compProps} />
更新:
我在 react 中使用 TS,作为强类型语言,它不允许我将未定义的 Prop 作为初始值。我设法通过首先检查 Prop 来解决这个问题。
{ compProps && 
    <CustomComp {...compProps} /> }

最佳答案

是的,我们可以这样做,但是您需要在大括号内使用扩展运算符。

 const compProps = { 
   label: 'Test Label',
   value: 'Test Value',
   icon: 'test-icon'
 }

 <CustomComp {...compProps} />
在子组件中,您可以访问这样的 Prop props.label

关于reactjs - 是否可以使用展开运算符来设置 react 组件 Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69459769/

相关文章:

javascript - 传递调用函数的 => 而不是仅仅传递函数本身

html - 如何在 react 中安全地呈现 html?

javascript - setState 也会改变屏幕 Prop

javascript - 如何使用 ReactJs 实现 `Search box` 到 `props items`

javascript - react 状态更新不正确

reactjs - 创建React App添加第三方js库

javascript - 如何使用map将数据从reactJs上的组件传递到另一个组件?

javascript - react : Why is the DIV that I wrap my JSX in suddenly very narrow and not allowing my layout to expand?

reactjs - 连接 PureComponent 可以吗?

javascript - 检测包含 http 请求的 forEach 循环结束?