在 React 中传递属性但抛出异常

问题描述 投票:0回答:1

有时我们都会做一些共同的事情。将 dom 元素包裹在自定义组件中

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

此示例中的自定义组件包装了

button
,它具有属性
id
title
,但没有
nonDomProp
,因此我收到一条警告,这是有意义的,因为包装的
button
DOM 元素中不存在 nonDomProp,并且我我只是使用展开运算符将所有属性传递给
button
DOM 元素
<button {...props} />

解决此问题的一种方法是仅手动传递

button
将使用的道具,但我想知道是否有一种方法可以告诉展开运算符使用所有传递的
...props
但忽略
nonDomProp

我尝试进行谷歌搜索,但无法找到我要找的东西,所以我想也许 SO 会为我指明正确的方向。

javascript reactjs spread-syntax
1个回答
1
投票

您可以使用以下方法解构 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

© www.soinside.com 2019 - 2024. All rights reserved.