跳至内容

@stylistic/

jsx-self-closing-comp

禁止为没有子元素的组件添加额外的结束标签。

没有子元素的组件可以自闭合,以避免不必要的额外结束标签。

规则详情

此规则的错误代码示例

jsx
var HelloJohn = <Hello name="John"></Hello>;

var HelloJohnCompound = <Hello.Compound name="John"></Hello.Compound>;

此规则的正确代码示例

jsx
var contentContainer = <div className="content"></div>;

var intentionalSpace = <div>{' '}</div>;

var HelloJohn = <Hello name="John" />;

var HelloJohnCompound = <Hello.Compound name="John" />;

var Profile = <Hello name="John"><img src="picture.png" /></Hello>;

var ProfileCompound = <Hello.Compound name="John"><img src="picture.png" /></Hello.Compound>;

var HelloSpace = <Hello>{' '}</Hello>;

规则选项

该规则可以接受一个参数来选择应该自闭合的标签类型。默认情况下,自定义组件标签和 html 标签应该自闭合。

js
...
"@stylistic/jsx/jsx-self-closing-comp": ["error", {
  "component": true,
  "html": true
}]
...

component

当为 true 时,自定义组件标签应该自闭合。

此规则的错误代码示例

jsx
var HelloJohn = <Hello name="John"></Hello>;

此规则的正确代码示例

jsx
var contentContainer = <div className="content"></div>;

var intentionalSpace = <div>{' '}</div>;

var HelloJohn = <Hello name="John" />;

var HelloJohnCompound = <Hello.Compound name="John" />;

var Profile = <Hello name="John"><img src="picture.png" /></Hello>;

var ProfileCompound = <Hello.Compound name="John"><img src="picture.png" /></Hello.Compound>;

html

当为 true 时,html 组件标签应该自闭合。

此规则的错误代码示例

jsx
var contentContainer = <div className="content"></div>;

此规则的正确代码示例

jsx
var contentContainer = <div className="content" />;

var contentContainer = <div className="content"><div /></div>;

var intentionalSpace = <div>{' '}</div>;