传递属性但在 React 中产生异常

Pass properties but make exceptions in React

有些事情我们有时都会做。在自定义组件中包装 dom 个元素

<CustomComponet id="abc" title="abc" nonDomProp="abc" ...andsoforth />

此示例中的自定义组件包装了 button,它具有属性 idtitle,但没有 nonDomProp,所以我收到一个警告,这是有道理的,因为 nonDomProp 没有t 存在于包装的 button DOM 元素中,我只是将所有道具传递给 button DOM 带有扩展运算符 <button {...props} />

的元素

解决这个问题的一种方法是手动仅传递 button 将使用的道具,但我想知道是否有办法告诉传播运算符使用所有传递的 ...props但要忽略 nonDomProp.

我已尝试进行 Google 搜索,但未能找到我正在寻找的内容,所以我想也许 SO 会为我指明正确的方向。

您可以使用以下方法解构 props 对象:

const { nonDomProp, ...propsButton } = props;
return(
 <button {...propsButton} />
)

或直接来自 CustomComponent 函数的参数:

const CustomComponent = ({ nonDomProp, ...props }) => {
...
return(
 <button {...props} />
)
}

文档:https://github.com/tc39/proposal-object-rest-spread#rest-properties