Skip to content
← Back to rules

react/自闭合组件 风格

An auto-fix is available for this rule.

它的作用

检测没有子元素的组件,这些组件可以使用自闭合语法,以避免不必要的额外闭合标签。

为什么这是个问题?

没有子元素的组件不需要显式的闭合标签。使用自闭合语法可以使代码更加简洁,减少视觉上的杂乱。同时,这也符合 React 和 JSX 中对空元素的常见约定。

允许包含空白字符的自闭合组件,但不包括同时包含换行符的情况。

示例

此规则的错误代码示例:

jsx
const elem = <Component linter="oxlint"></Component>;
const dom_elem = <div id="oxlint"></div>;
const welem = <div id="oxlint"></div>;

此规则的正确代码示例:

jsx
const elem = <Component linter="oxlint" />;
const welem = <Component linter="oxlint"> </Component>;
const dom_elem = <div id="oxlint" />;

配置

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

component

type: boolean

default: true

是否强制自闭合自定义组件。

html

type: boolean

default: true

是否强制自闭合原生 HTML 元素。

如何使用

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

json
{
  "plugins": ["react"],
  "rules": {
    "react/self-closing-comp": "error"
  }
}
bash
oxlint --deny react/self-closing-comp --react-plugin

参考资料