5. React 组件的工作原理

0 阅读3分钟

React 组件的工作原理

React 组件 是 React 应用的 核心部分,所有的 UI 和 交互逻辑 基本上都是通过 组件 来构建的

React 组件可以分为 两种 主要类型:

  1. 函数式组件(Functional Components)
  2. 类组件(Class Components)

在现代 React 开发中,函数式组件 已成为 主流,尤其是与 React Hooks 配合使用时。

1 React 组件的基础知识

一个组件 本质上是 一个 返回 React 元素 的 函数 或 类

函数式组件

// 函数组件
function Greeting(props) {
  return <h1>Hello, {props.name}!</h1>;
}

Greeting 是一个接收 props 作为参数 的 函数式组件,返回一个 h1 元素,显示 传入的 name 属性。

类组件

// 类组件
class Greeting extends React.Component {
  render() {
    return <h1>Hello, {this.props.name}!</h1>;
  }
}

Greeting 是一个 继承自 React.Component类组件。在 render() 方法 中,类组件 返回一个 h1 元素,显示 传入的 name 属性。

2 React 组件的核心概念

2.1 Props(属性)

props 是组件的 输入参数,它是一个 只读对象,用来从 父组件 传递数据到 子组件。通过 props子组件 可以访问 父组件数据行为

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

// 使用组件并传递 props
<Greeting name="Alice" />

2.2 State(状态)

state组件内部数据源,用来 存储管理 组件的 动态数据。只有 类组件函数组件(使用 useState hook)才能使用 state

import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);  // 初始化状态

  const increment = () => {
    setCount(count + 1);  // 更新状态
  };

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={increment}>Increment</button>
    </div>
  );
}

在函数组件中,通过 useState Hook 来管理 state,并且可以通过 setCount 来更新 count

2.3 生命周期方法

类组件生命周期

类组件 可以使用 生命周期方法 来处理组件在 不同阶段 的行为。常见的生命周期方法有:

  • componentDidMount() :组件 第一次渲染后 调用,适合 发起网络请求 等操作;
  • componentDidUpdate() :组件 更新后 调用,适合在更新后 执行某些 副作用
  • componentWillUnmount() :组件从 DOM 中 移除之前 调用,适合 清理资源(如 定时器、事件监听 等)。
class MyComponent extends React.Component {
  componentDidMount() {
    console.log('组件已挂载');
  }

  componentDidUpdate(prevProps, prevState) {
    console.log('组件已更新');
  }

  componentWillUnmount() {
    console.log('组件将卸载');
  }

  render() {
    return <h1>Hello, {this.props.name}</h1>;
  }
}

2.4 Hooks(函数组件中的功能增强)

React 16.8 引入了 Hooks,允许在 函数组件 中使用 state生命周期 等功能。常用的 Hooks 包括:

  • useState:用来 添加状态
  • useEffect:用来 执行副作用,如 网络请求、订阅 等;
  • useContext:用来在 函数组件 中使用 上下文(Context);
  • useRef:用来 获取 DOM 元素引用
useState 示例
import React, { useState } from 'react';

function Counter() {
  const [count, setCount] = useState(0);  // 初始化状态

  const increment = () => setCount(count + 1);

  return (
    <div>
      <h1>Count: {count}</h1>
      <button onClick={increment}>Increment</button>
    </div>
  );
}
useEffect 示例
import React, { useState, useEffect } from 'react';

function Timer() {
  const [seconds, setSeconds] = useState(0);

  useEffect(() => {
    const timer = setInterval(() => setSeconds((prev) => prev + 1), 1000);

    // Cleanup function
    return () => clearInterval(timer);
  }, []);  // 空数组表示只在组件挂载时执行

  return <h1>Time: {seconds} seconds</h1>;
}

3 React 组件间通信

父子组件传值(通过 props

父组件 通过 props 向 子组件 传递数据,子组件 可以通过 props 来 读取 这些数据。

function Parent() {
  return <Greeting name="Alice" />;
}

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

子向父组件传值(通过回调函数)

子组件 通过 调用 父组件 传递下来的 回调函数向 父组件 传递数据。

function Parent() {
  const handleNameChange = (newName) => {
    console.log('New Name:', newName);
  };

  return <Child onNameChange={handleNameChange} />;
}

function Child(props) {
  return (
    <div>
      <button onClick={() => props.onNameChange('Bob')}>Change Name</button>
    </div>
  );
}

4 React 组件性能优化

React.memo:对于 函数组件,可以使用 React.memo 来避免 不必要的 重新渲染,特别是当组件 接收到 相同的 props

const MemoizedComponent = React.memo(Component);

shouldComponentUpdate:在 类组件 中,可以通过 shouldComponentUpdate 方法 控制组件 是否 重新渲染。