• React的类式组件和函数式组件之间有什么区别?


    React 中的类组件和函数组件是两种不同的组件编写方式,它们之间有一些区别。

    语法和写法:类组件是使用类的语法进行定义的,它继承自 React.Component 类,并且需要实现 render() 方法来返回组件的 JSX。函数组件是使用函数的语法进行定义的,它接收一个 props 对象作为参数,并返回组件的 JSX。

    示例:类组件

    1. class MyComponent extends React.Component {
    2. render() {
    3. return
      Hello, {this.props.name}
      ;
    4. }
    5. }

    示例:函数组件

    1. function MyComponent(props) {
    2. return <div>Hello, {props.name}</div>;
    3. }

    状态管理:在类组件中,可以使用 state 属性来存储和管理组件的内部状态。state 是一个可变的对象,当状态发生变化时,组件会重新渲染。函数组件在 React 16.8 引入的 Hooks 特性后,也可以使用 useState Hook 来管理组件的状态。 示例:类组件中的状态管理

    1. class Counter extends React.Component {
    2. constructor(props) {
    3. super(props);
    4. this.state = { count: 0 };
    5. }
    6. increment() {
    7. this.setState({ count: this.state.count + 1 });
    8. }
    9. render() {
    10. return (
    11. <div>
    12. Count: {this.state.count}
    13. <button onClick={() => this.increment()}>Increment</button>
    14. </div>
    15. );
    16. }
    17. }

    示例:函数组件中的状态管理(使用 useState Hook)

    1. function Counter() {
    2. const [count, setCount] = React.useState(0);
    3. const increment = () => {
    4. setCount(count + 1);
    5. };
    6. return (
    7. <div>
    8. Count: {count}
    9. <button onClick={increment}>Increment</button>
    10. </div>
    11. );
    12. }

    示例:函数组件中的生命周期模拟(使用 useEffect Hook)

    1. function MyComponent(props) {
    2. React.useEffect(() => {
    3. console.log('Component mounted');
    4. return () => {
    5. console.log('Component will unmount');
    6. };
    7. }, []);
    8. React.useEffect(() => {
    9. console.log('Component updated');
    10. });
    11. return <div>Hello, {props.name}</div>;
    12. }

    总的来说,类组件和函数组件都可以实现相同的功能,但随着 React 的发展,函数组件在代码简洁性、可测试性和性能方面具有一些优势,并且在使用 Hooks 后,函数组件可以更方便地处理状态和副作用。因此,函数组件逐渐成为 React 中的主要编写方式。



     

  • 相关阅读:
    Kafka - 09 Kafka副本 | Leader选举流程 | Follower故障 | Leader故障
    SoringBoot特点
    什么时候用@MapperScan 注解?
    微服务框架 SpringCloud微服务架构 20 RestClient 操作索引库 20.2 hotel 数据结构分析
    Linux- 僵尸进程(Zombie Process)
    Kotlin 中的数据类型有隐式转换吗?
    C语言:strlen() --- 计算字符串长度
    YOLOv8学习
    vsphere centos虚拟机创建
    【JMeter】控制器If Controller
  • 原文地址:https://blog.csdn.net/m0_74265396/article/details/133756486