React 详解

108 阅读2分钟

React 详解

React 是一个用于构建用户界面的 JavaScript 库,由 Facebook 开发并开源。以下是 React 的详细解析:

1. React 核心概念

1.1 JSX (JavaScript XML)

JSX 是 JavaScript 的语法扩展,允许在 JavaScript 中编写类似 HTML 的代码:

const element = <h1>Hello, world!</h1>;

特点:

  • 不是字符串也不是 HTML
  • 最终会被转译为 React.createElement() 调用
  • 可以嵌入 JavaScript 表达式使用 {}

1.2 组件

React 应用由组件构成,分为两种类型:

函数组件

function Welcome(props) {
  return <h1>Hello, {props.name}</h1>;
}

类组件

class Welcome extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

1.3 Props 和 State

  • Props:从父组件传递给子组件的数据(只读)
  • State:组件内部管理的可变数据
class Counter extends React.Component {
  constructor(props) {
    super(props);
    this.state = { count: 0 };
  }

  render() {
    return <div>{this.state.count}</div>;
  }
}

1.4 生命周期方法(类组件)

主要生命周期方法:

  • componentDidMount():组件挂载后调用
  • componentDidUpdate():组件更新后调用
  • componentWillUnmount():组件卸载前调用

2. React Hooks

React 16.8 引入的新特性,让函数组件也能使用状态和其他 React 特性。

2.1 常用 Hooks

useState

const [count, setCount] = useState(0);

useEffect

useEffect(() => {
  // 相当于 componentDidMount 和 componentDidUpdate
  document.title = `You clicked ${count} times`;
  
  return () => {
    // 清理函数,相当于 componentWillUnmount
  };
}, [count]); // 仅在 count 更改时更新

useContext

const value = useContext(MyContext);

useReducer

const [state, dispatch] = useReducer(reducer, initialState);

2.2 自定义 Hook

可以提取组件逻辑到可重用的函数中:

function useFriendStatus(friendID) {
  const [isOnline, setIsOnline] = useState(null);

  useEffect(() => {
    // 订阅状态
    return () => {
      // 取消订阅
    };
  });

  return isOnline;
}

3. React 高级特性

3.1 上下文 (Context)

跨组件层级传递数据:

const MyContext = React.createContext(defaultValue);

// 提供者
<MyContext.Provider value={/* 某个值 */}>

// 消费者
<MyContext.Consumer>
  {value => /* 基于上下文值进行渲染 */}
</MyContext.Consumer>

3.2 Refs

访问 DOM 节点或 React 元素:

const myRef = useRef(null);

// 访问
myRef.current.focus();

// 绑定
<input ref={myRef} />

3.3 高阶组件 (HOC)

接收组件并返回新组件的函数:

function withSubscription(WrappedComponent) {
  return class extends React.Component {
    // ...
    render() {
      return <WrappedComponent data={this.state.data} {...this.props} />;
    }
  };
}

3.4 Render Props

使用值为函数的 prop 在组件间共享代码:

<DataProvider render={data => (
  <h1>Hello {data.target}</h1>
)}/>

4. React 性能优化

4.1 避免不必要的渲染

  • React.memo:记忆函数组件
  • shouldComponentUpdate:类组件中控制更新
  • useMemo:记忆计算结果
  • useCallback:记忆回调函数

4.2 代码分割

使用 React.lazySuspense

const OtherComponent = React.lazy(() => import('./OtherComponent'));

function MyComponent() {
  return (
    <React.Suspense fallback={<div>Loading...</div>}>
      <OtherComponent />
    </React.Suspense>
  );
}

5. React 生态系统

5.1 状态管理

  • Redux:可预测的状态容器
  • MobX:简单可扩展的状态管理
  • Context API:内置的简单状态管理方案

5.2 路由

  • React Router:最流行的路由解决方案
<Router>
  <Switch>
    <Route path="/about" component={About} />
    <Route path="/users" component={Users} />
    <Route path="/" component={Home} />
  </Switch>
</Router>

5.3 样式方案

  • CSS Modules
  • Styled-components
  • Emotion
  • Tailwind CSS

6. React 18 新特性

  • 并发渲染 (Concurrent Rendering)
  • 自动批处理 (Automatic Batching)
  • 新的 Suspense 特性
  • 新的根 API (createRoot)
  • 过渡 API (startTransition)
// React 18 新根API
import { createRoot } from 'react-dom/client';

const root = createRoot(document.getElementById('root'));
root.render(<App />);

React 是一个不断发展的库,建议定期查阅官方文档以获取最新信息。