返回

在Cc里用class和function实现counter

前端

前言

随着CcFragment支持hook了,私底下有小伙伴问我,在 什么 场景下使用hook,才能体现出hook的精髓,以及什么时候支持useStore和useReducer。 为了进一步解释CcFragment和hook,我们来用cc完成一个有意思的counter示例,让大家进一步理解CcFragment和hook的精髓。

使用class实现counter

首先,我们使用class来实现一个counter。在cc中,创建一个名为Counter的类,并在类中定义一个名为count的属性,用于存储计数器。同时,定义一个名为incrementCount的方法,用于增加计数器。

class Counter {
  count = 0;

  incrementCount() {
    this.count++;
  }
}

然后,在组件中创建一个Counter实例,并使用setState方法更新计数器。

const App = () => {
  const [counter, setCounter] = useState(new Counter());

  const handleClick = () => {
    counter.incrementCount();
    setCounter(counter);
  };

  return (
    <div>
      <p>Count: {counter.count}</p>
      <button onClick={handleClick}>Increment</button>
    </div>
  );
};

使用function实现counter

接下来,我们使用function来实现一个counter。在cc中,创建一个名为useCounter的函数,该函数返回一个包含count和incrementCount方法的对象。

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

  const incrementCount = () => {
    setCount(count + 1);
  };

  return { count, incrementCount };
};

然后,在组件中使用useCounter函数,并将其返回的对象解构赋值给count和incrementCount变量。

const App = () => {
  const { count, incrementCount } = useCounter();

  const handleClick = () => {
    incrementCount();
  };

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

使用CcFragment和hook实现counter

最后,我们使用CcFragment和hook来实现一个counter。在cc中,创建一个名为Counter的组件,并在组件中使用CcFragment将count和incrementCount变量包裹起来。

const Counter = () => {
  const { count, incrementCount } = useCounter();

  return (
    <CcFragment>
      <p>Count: {count}</p>
      <button onClick={incrementCount}>Increment</button>
    </CcFragment>
  );
};

然后,在组件中使用Counter组件。

const App = () => {
  return (
    <div>
      <Counter />
    </div>
  );
};

比较class、function和hook实现counter

通过以上三种方式实现的counter,在功能上都是相同的,但是它们在使用方式上却存在着一些差异。

  • 使用class实现counter,需要在组件中创建一个Counter实例,并使用setState方法更新计数器。这种方式相对比较复杂,而且需要对class有比较深入的了解。
  • 使用function实现counter,只需要创建一个useCounter函数,并将其返回的对象解构赋值给count和incrementCount变量。这种方式相对比较简单,而且不需要对function有比较深入的了解。
  • 使用CcFragment和hook实现counter,只需要在组件中使用CcFragment将count和incrementCount变量包裹起来。这种方式是最简单的一种,而且不需要对CcFragment和hook有比较深入的了解。

结论

通过本示例,我们可以看到,CcFragment和hook可以帮助我们更轻松地实现组件的复用和状态管理。对于那些需要经常编写组件的小伙伴来说,CcFragment和hook是一个非常有用的工具。

参考