1
4

1 回答 1

1

正如评论中所讨论的,我将发布上面 HOC 的自定义钩子对应项:

据我在您的代码中了解,您需要一个 HOC,您可以将其“挂钩”到组件上,它会执行计数。

因此,您可以创建一个自定义挂钩:

const useCounter = (default = 0) => {
      const [count, setCount] = useState(default);
      const [add, setAdd] = useState(0);
      const handleClick = (base = 0) => {
          setCount(count + base + add);
      };
      const onSetAdd = (e) => setAdd(e.target.value);
      
      return {count, handleClick, onSetAdd};
}

现在把它挂在一个功能组件中:


const LikesCount = () => {
    const {count, handleClick, onSetAdd} = useCounter(0);
    const onAddOne = () => handleClick(); // default is 1, so passing none = one
    const onAddTwo = () => handleClick(2);
    const onAddThree = () => handleClick(3);
   

    return (
        <div>
            <input type="number" onChange={onSetAdd} value={add} />
            {count} <br />
            <button onClick={onAddOne}>Like</button>
            <button onClick={onAddTwo}>Add 2</button>
            <button onClick={onAddThree}>Add 3</button>
        </div>
    );
}

export default LikesCount;

就是这样,您可以在您想要拥有计数器的任何组件上添加 ff 代码:

const {count, handleClick} = useCounter(0);

上面的代码与您提供的示例 HOC 完全相同。

于 2021-06-07T14:32:00.843 回答