Skip to content
← Back to rules

react/static-components 正确性

作用

验证组件是否为静态组件——在模块作用域中定义,而不是在每次渲染时重新创建——因为动态重新创建的组件会重置状态,并导致过度重新渲染。

由 React Compiler 提供支持,该编译器每个文件只运行一次,并与其他 React Compiler 规则共享。移植自 react-hooks/static-components

为什么这是不好的?

在渲染期间创建的组件在每次渲染时都会获得新的标识,因此 React 每次都会卸载并重新挂载它——重置其全部状态,并重新渲染其整个子树。

示例

此规则下的错误代码示例:

jsx
function Example(props) {
  const Component = createComponent();
  return <Component />;
}

此规则下的正确代码示例:

jsx
function Inner(props) {
  return <div>{props.text}</div>;
}
function Outer() {
  return <Inner text="hello" />;
}

如何使用

To enable this rule using the config file or in the CLI, you can use:

json
{
  "plugins": ["react"],
  "rules": {
    "react/static-components": "error"
  }
}
ts
import { defineConfig } from "oxlint";

export default defineConfig({
  plugins: ["react"],
  rules: {
    "react/static-components": "error",
  },
});
bash
oxlint --deny react/static-components --react-plugin

版本

此规则已在 vnext 中添加。

参考