react/no-this-in-sfc Correctness
它的作用
阻止在无状态函数组件中使用 this。
这为什么不好?
在 React 中,无状态函数组件(SFC)通过函数参数接收 props 和 context, 而不是通过 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>;
}
}如何使用
To enable this rule using the config file or in the CLI, you can use:
json
{
"plugins": ["react"],
"rules": {
"react/no-this-in-sfc": "error"
}
}ts
import { defineConfig } from "oxlint";
export default defineConfig({
plugins: ["react"],
rules: {
"react/no-this-in-sfc": "error",
},
});bash
oxlint --deny react/no-this-in-sfc --react-plugin版本
此规则在 v1.37.0 中添加。
