Skip to content
← Back to rules

react/jsx-props-no-spreading 风格

它的作用

禁止在 JSX 属性中使用展开操作符

为什么这是不好的?

强制要求对任何 JSX 属性都不允许使用展开操作符。这通过更明确地表达组件接收了哪些属性,提升了代码的可读性。
同时,它也有助于维护性,避免意外传递额外的属性,并允许 React 在向 HTML 元素传递无效的 HTML 属性时发出警告。

示例

此规则的 错误 代码示例:

jsx
<App {...props} />
<MyCustomComponent {...props} some_other_prop={some_other_prop} />
<img {...props} />

此规则的 正确 代码示例:

jsx
const {src, alt} = props;
const {one_prop, two_prop} = otherProps;
<MyCustomComponent one_prop={one_prop} two_prop={two_prop} />
<img src={src} alt={alt} />

配置

该规则接受一个配置对象,包含以下属性:

custom

type: "ignore" | "enforce"

default: "enforce"

custom 设置为 ignore 会忽略所有自定义 JSX 标签,例如 AppMyCustomComponent 等。默认值为 enforce

exceptions

type: string[]

default: []

例外项会反转特定组件的强制行为。
例如:

  • 如果 html 设置为 ignore,则对 div 的例外将对 <div> 元素强制执行该规则。
  • 如果 custom 设置为 enforce,则对 Foo 的例外将忽略对 <Foo> 组件的规则。

这允许你为单个组件覆盖整体设置。

explicitSpread

type: "ignore" | "enforce"

default: "enforce"

explicitSpread 设置为 ignore 会忽略那些显式列出展开对象中所有属性的展开操作符。默认值为 enforce

html

type: "ignore" | "enforce"

default: "enforce"

html 设置为 ignore 会忽略所有 HTML JSX 标签,例如 divimg 等。默认值为 enforce

如何使用

要通过配置文件或 CLI 启用 此规则,可以使用:

json
{
  "plugins": ["react"],
  "rules": {
    "react/jsx-props-no-spreading": "error"
  }
}
bash
oxlint --deny react/jsx-props-no-spreading --react-plugin

参考资料