Skip to content

useReactFunctionComponents

¥Summary

¥How to configure

biome.json
{
"linter": {
"rules": {
"style": {
"useReactFunctionComponents": "error"
}
}
}
}

¥Description

强制要求组件定义为函数,而不能定义为类。

¥Enforce that components are defined as functions and never as classes.

React 特别允许用户使用函数或类创建组件。然而,通常建议使用函数。此规则强制要求使用函数组件。

¥React in particular allows users to create components using functions or classes. However, using functions is generally preferred. This rule enforces the use of function components.

此规则对实现了 componentDidCatch 接口的类组件例外,因为 React 目前没有替代的 hook。此函数通常用于定义错误边界。建议定义一次错误边界,然后在整个应用中重复使用。

¥This rule makes an exception for class components that implement componentDidCatch because there is currently no hook alternative for React. This function is typically used for defining error boundaries. It’s recommended to define your error boundary once and then reuse it across your application.

如果你使用的是 Preact,它有一个 useErrorBoundary 钩子。

¥If you are using Preact, it has a useErrorBoundary hook.

¥Examples

¥Invalid

class Foo extends React.Component {
render() {
return (
<div>This is a class component.</div>
);
}
}
code-block.jsx:1:1 lint/style/useReactFunctionComponents ━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━━

Class components are not allowed. Function components are the preferred way to write components.

> 1 │ class Foo extends React.Component {
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
> 2 │ render() {
> 3 │ return (
> 4 │ <div>This is a class component.</div>
> 5 │ );
> 6 │ }
> 7 │ }
^
8 │

Refactor this into a function component.

¥Valid

function Foo() {
return <div>This is a function component.</div>;
}

¥Related links