React 组件开发

232 阅读2分钟

一、类组件与函数组件对比

1. 类组件开发模式

class App extends React.Component {
  constructor() {
    super();
    this.state = { count: 0 };
    // 方法绑定方案二:构造器绑定
    // this.add = this.add.bind(this);
  }

  add() {
    this.setState({ count: this.state.count + 1 });
  }

  // 箭头函数方案三:避免绑定
  // add = () => {
  //   this.setState({ count: this.state.count + 1 });
  // }

  render() {
    return (
      <button onClick={this.add.bind(this)}>
        点击次数: {this.state.count}
      </button>
    );
  }
}

核心要点:

  • 必须通过super()调用父类构造函数
  • 状态管理使用this.statesetState()
  • 事件处理需要处理this指向问题(三种解决方案)
  • 生命周期方法控制组件行为

2. 函数组件与Hooks

import { useState, useEffect } from 'react';

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

  useEffect(() => {
    console.log('组件挂载或更新');
    return () => console.log('组件卸载');
  }, [count]);

  return (
    <button onClick={() => setCount(c => c + 1)}>
      点击次数: {count}
    </button>
  );
}

Hooks优势:

  • useState:简化状态管理
  • useEffect:整合生命周期逻辑
  • 更好的逻辑复用能力
  • 更简洁的代码结构

二、组件通信体系

1. 父子组件通信

// 父组件
class Parent extends React.Component {
  getMsg = (msg) => {
    console.log('来自子组件:', msg);
  }

  render() {
    return <Child onSend={this.getMsg} />;
  }
}

// 子组件
const Child = ({ onSend }) => (
  <button onClick={() => onSend('Hello Parent')}>
    发送消息
  </button>
);

2. 跨级组件通信(Context API)

const ThemeContext = React.createContext('light');

// 提供者
function App() {
  return (
    <ThemeContext.Provider value="dark">
      <Toolbar />
    </ThemeContext.Provider>
  );
}

// 消费者
function Toolbar() {
  return (
    <ThemeContext.Consumer>
      {value => <div>当前主题: {value}</div>}
    </ThemeContext.Consumer>
  );
}

3. 兄弟组件通信

通过共同的父组件进行状态提升:

function Parent() {
  const [shared, setShared] = useState('');

  return (
    <>
      <ChildA onUpdate={setShared} />
      <ChildB value={shared} />
    </>
  );
}

三、生命周期与副作用管理

类组件生命周期

  • 挂载阶段:constructor → render → componentDidMount
  • 更新阶段:render → componentDidUpdate
  • 卸载阶段:componentWillUnmount

Hooks实现生命周期

useEffect(() => {
  // componentDidMount + 依赖更新
  console.log('组件挂载或更新');
  return () => {
    // componentWillUnmount
    console.log('组件卸载');
  };
}, [dependencies]); // 空数组表示仅执行一次

四、最佳实践建议

  1. 组件设计原则
  • 保持组件单一职责
  • 合理划分容器组件与展示组件
  • 优先使用函数组件+Hooks
  1. 性能优化
  • 使用React.memo进行组件缓存
  • 合理使用useCallback/useMemo
  • 避免不必要的渲染
  1. 状态管理选择
  • 简单场景使用组件状态
  • 复杂交互使用Context API
  • 大型应用推荐Redux/MobX

五、技术选型建议

特性类组件函数组件+Hooks
代码复杂度较高较低
逻辑复用HOC/Render Props自定义Hook
学习曲线较平缓需要理解闭包特性
未来兼容性逐步演进React主推方向

建议新项目优先使用函数组件+Hooks开发,老项目逐步进行迁移改造。理解类组件的工作原理对于深入掌握React运行机制仍然非常重要。