我想使用扩展运算符来设置组件 Prop 。这主要是因为我不想为每个 props 值使用 state。这可能吗?下面的代码返回一个错误,指出 Prop 丢失。提前致谢!
const compProps = {
label: 'Test Label',
value: 'Test Value',
icon: 'test-icon'
}
<CustomComp {...compProps} />
更新:我在 react 中使用 TS,作为强类型语言,它不允许我将未定义的 Prop 作为初始值。我设法通过首先检查 Prop 来解决这个问题。
{ compProps &&
<CustomComp {...compProps} /> }
最佳答案
是的,我们可以这样做,但是您需要在大括号内使用扩展运算符。
在子组件中,您可以访问这样的 Prop const compProps = {
label: 'Test Label',
value: 'Test Value',
icon: 'test-icon'
}
<CustomComp {...compProps} />
props.label
关于reactjs - 是否可以使用展开运算符来设置 react 组件 Prop ?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/69459769/