欢迎来到尧图网

客户服务 关于我们

您的位置:首页 > 财经 > 金融 > React--函数组件和类组件

React--函数组件和类组件

2025/6/20 0:37:02 来源:https://blog.csdn.net/wl_qianduan/article/details/148106479  浏览:    关键词:React--函数组件和类组件

React 中的函数组件和类组件是两种定义组件的方式,它们有以下主要区别:

1. 语法与定义方式

  • 函数组件: 是 JavaScript 函数,接收 props 作为参数,返回 JSX。

    const MyComponent = (props) => {return <div>Hello, {props.name}</div>;
    };
    
  • 类组件: 继承自 React.Component,必须定义 render() 方法返回 JSX。

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

2. 状态管理

  • 函数组件: 最初无状态,需使用 Hooks(如 useState)管理状态。

    const Counter = () => {const [count, setCount] = useState(0);return <button onClick={() => setCount(count + 1)}>{count}</button>;
    };
    
  • 类组件: 通过 this.state 和 this.setState 管理状态。

    class Counter extends React.Component {state = { count: 0 };increment = () => {this.setState({ count: this.state.count + 1 });};render() {return <button onClick={this.increment}>{this.state.count}</button>;}
    }
    

3. 生命周期方法

  • 函数组件: 使用 useEffect Hook 替代生命周期方法。

    useEffect(() => {// 组件挂载后执行return () => {// 组件卸载前执行};
    }, []); // 依赖项为空数组时,等效于 componentDidMount 和 componentWillUnmount
    
  • 类组件: 有完整的生命周期方法(如 componentDidMount、componentDidUpdate、componentWillUnmount)。

    class MyComponent extends React.Component {componentDidMount() {// 组件挂载后执行}componentWillUnmount() {// 组件卸载前执行}
    }
    

4. 性能优化

  • 函数组件: 通过 React.memo 浅比较 props 避免重复渲染。

    const MyComponent = React.memo((props) => {return <div>{props.value}</div>;
    });
    
  • 类组件: 通过 shouldComponentUpdate 或继承 React.PureComponent 实现。

    class MyComponent extends React.PureComponent {// 自动浅比较 props 和 state
    }
    

5. 上下文与 refs

  • 函数组件: 使用 useContext 和 useRef Hooks。

    const value = useContext(MyContext);
    const ref = useRef(null);
    
  • 类组件: 通过 static contextType 或 Context.Consumer,以及 React.createRef()。

    static contextType = MyContext;
    ref = React.createRef();
    

6. 适用场景

  • 函数组件: 更简洁,适合无状态组件或逻辑简单的组件,是 React 的推荐写法。
  • 类组件: 适合复杂逻辑(如需要访问生命周期方法或使用 this),但逐渐被函数组件替代。

总结

特性函数组件类组件
语法函数 / 箭头函数继承 React.Component
状态管理Hooks(如 useState)this.state 和 setState
生命周期useEffect Hook完整生命周期方法
性能优化React.memoshouldComponentUpdate
适用场景无状态 / 简单逻辑复杂逻辑 / 生命周期依赖

现代 React 开发中,函数组件配合 Hooks 已成为主流,因为它们更简洁、可复用性更高,并且能更好地处理状态和副作用。

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

热搜词