Skip to content

React 最佳实践

项目结构, naming 约定, accessibility, and clean code 原则 for React.

你将学到

  • 组织 files and folders for scalability
  • Naming 约定 and 组件模式
  • Accessibility as 首先-类 concern
  • Code quality: linting, 格式化, and code review

概念讲解

Project Structure

A good project structure scales with your team and codebase. A common approach is feature-based organization: group files by feature or domain (e.g., features/认证/, features/dashboard/) rather than by file type (组件/, Hook/, utils/). Each feature folder contains its components, hooks, tests, and types. Shared code goes in a shared/ or lib/ directory. This makes it easy to find all code related to a feature and to move or delete a feature without touching unrelated files. Keep the structure flat enough to navigate but organized enough to scale.

Naming Conventions

Consistent naming is crucial for readability. Components use PascalCase: UserProfile, SearchBar. Hooks start with use: useAuth, useDebounce. Event handlers start with handle: handleSubmit, handleClick. Props that are callbacks use on prefix: onSubmit, onChange. Boolean props use 是/有/应该: isLoading, hasError, shouldRender. Files match their default export: UserProfile.tsx exports UserProfile. Consistency matters more than the specific convention — pick one and enforce it with linting.

Accessibility

Accessibility (a11y) is not optional — it is a legal requirement and a moral imperative. Use semantic HTML: <button> for clickable actions (not <div onClick>), <nav> for navigation, <主要> for main content, <请求头> and <footer> for their respective areas. Provide alt text for images, aria-label for icon-only buttons, and label elements for form inputs. Manage focus for keyboard users (tab order, focus trapping in modals). Test with a screen reader and keyboard-only navigation. Libraries like react-aria and @radix-ui provide accessible primitives.

Code Quality

Enforce code quality with tooling. ESLint with eslint-plugin-react and eslint-plugin-react-Hook catches common mistakes (missing deps in useEffect, hook rule violations). Prettier formats code consistently. TypeScript provides type safety. Write tests for critical user flows. Review code for readability — code is read far more often than it is written. Keep components small and focused, extract reusable logic into custom hooks, and prefer composition over inheritance. Document complex logic with comments, but let clear naming and structure do most of the documentation work.

示例代码

              // Good: semantic HTML, accessible labels, clear naming.
function SearchBar({ onSearch, isLoading }) {
  const [query, setQuery] = useState("");

  const handleSubmit = (e) => {
    e.preventDefault();
    if (query.trim()) onSearch(query.trim());
  };

  return (
    <form onSubmit={handleSubmit} role="search">
      <label htmlFor="search-input" className="sr-only">Search</label>
      <input
        id="search-input"
        type="search"
        value={query}
        onChange={e => setQuery(e.target.value)}
        placeholder="Search articles..."
        aria-label="Search articles"
      />
      <button type="submit" disabled={isLoading}>
        {isLoading ? "Searching..." : "Search"}
      </button>
    </form>
  );
}

// Good: small, focused, reusable custom hook.
function useDebounce(value, delay) {
  const [debounced, setDebounced] = useState(value);
  useEffect(() => {
    const timer = setTimeout(() => setDebounced(value), delay);
    return () => clearTimeout(timer);
  }, [value, delay]);
  return debounced;
}
            

SearchBar uses 语义表单元素, accessible labels (sr-仅, aria-label), 清晰 naming (handleSubmit, isLoading), and 禁用状态. useDebounce 是小, focused, reusable Hook.

动手试一试

  • Code Minifier

    Minify 你的 production code for optimal delivery.

  • Code Diff

    Review code 更改期间 refactoring for 最佳实践 adherence.

常见错误

错误写法

Using <div onClick> 相反的 <button> for interactive 元素

正确做法

Use 语义 <button> for clickable 操作. 它是 keyboard accessible (输入/空间), focusable, and announced 正确地通过 screen readers. <div onClick> 需要 manual accessibility 工作那个是 简单到 获取错误.

错误写法

创建大 组件使用许多 responsibilities

正确做法

Keep 组件小 and focused on one thing. Extract reusable logic 到自定义 Hook, 拆分大 UI 到 smaller sub-组件, and aim for 组件 under 150-200 行. 小组件是 easier 到测试, reuse, and reason 关于.

练习 React 最佳实践

3 个练习

练习 React 最佳实践

查阅不认识的术语

新手友好的术语表用大白话解释编程术语——变量、函数、DOM、Promise 等等。

查看术语表

动手做项目

通过引导式项目应用所学,含起始代码与解决方案。

查看项目

解读错误信息

用大白话解释常见错误——什么意思、为什么发生、如何修复。

查看错误