react/no-this-in-sfc 正确性
它做了什么
防止在无状态函数组件中使用 this。
为什么这是个问题?
在 React 中,无状态函数组件(SFC)通过函数参数接收属性和上下文,而不是通过 this。在 SFC 中使用 this 通常表明在从类组件转换时出错,或对两种组件风格不熟悉。
示例
此规则的错误代码示例:
jsx
function Foo(props) {
return <div>{this.props.bar}</div>;
}
function Foo(props) {
const { bar } = this.props;
return <div>{bar}</div>;
}
const Foo = (props) => (this.props.foo ? <span>{props.bar}</span> : null);此规则的正确代码示例:
jsx
function Foo(props) {
return <div>{props.bar}</div>;
}
function Foo({ bar }) {
return <div>{bar}</div>;
}
class Foo extends React.Component {
render() {
return <div>{this.props.bar}</div>;
}
}如何使用
要通过配置文件或 CLI 启用此规则,可以使用:
json
{
"plugins": ["react"],
"rules": {
"react/no-this-in-sfc": "error"
}
}bash
oxlint --deny react/no-this-in-sfc --react-plugin