【问题标题】:React throws custom hook type error related to onClick eventReact 抛出与 onClick 事件相关的自定义钩子类型错误
【发布时间】:2021-10-03 11:31:31
【问题描述】:

我尝试并创建了一个新的自定义钩子,但遇到了如下所示的 onClick 类型编译错误

Failed to compile.

/Users/ryankim/personal/react/my-react-app/src/component/NCounterTwo.tsx
TypeScript error in /Users/ryankim/personal/react/my-react-app/src/component/NCounterTwo.tsx(11,15):
Type 'number | (() => void)' is not assignable to type 'MouseEventHandler<HTMLButtonElement> | undefined'.
  Type 'number' is not assignable to type 'MouseEventHandler<HTMLButtonElement> | undefined'.  TS2322

这是代码

import React from "react";
import useCounter from "../hooks/NCounterHook";

const NCounterTwo = () => {
  const initialValue = 0;
  const [counter, handleIncrement, handleDecrement, reset] = useCounter(initialValue);

  return (
    <div>
      <div>Counter= {counter}</div>
      <button onClick={handleIncrement}>Increment</button> // onClick shows squiggly line
      <button onClick={handleDecrement}>Decrement</button> // onClick shows squiggly line
      <button onClick={reset}>Reset</button>               // onClick shows squiggly line 
    </div>
  );
};

export default NCounterTwo;
import { useState } from "react";

const useCounter = (initValue = 0) => {
  const [counter, setCounter] = useState(0);

  const handleIncrement = () => {
    console.log('handleIncrement clicked');
    setCounter((prevCounter) => prevCounter + 1);
  };

  const handleDecrement = () => {
    console.log('handleDecrement clicked');
    setCounter((prevCounter) => prevCounter - 1);
  };

  const reset = () => setCounter(initValue);

  return [counter, handleIncrement, handleDecrement, reset];
};

export default useCounter;

我尝试将 onClick 函数更改为 onClick = {() => handleIncrement} 之类的箭头函数,然后波浪线消失了,但现在即使我单击“增量”或“减量”按钮,它也根本不起作用。

我不知道代码有什么问题以及如何修复它。

== 答案 ==

感谢龙的回答。正如 Long 所说,我需要用括号调用一个函数。但是修复后又引入了另一个错误

This expression is not callable.
  Not all constituents of type 'number | (() => void)' are callable.
    Type 'number' has no call signatures. 

当状态和函数在自定义钩子中作为数组重组返回时,它们应该使用 const 进行强制转换。

【问题讨论】:

  • 出色的修复。

标签: reactjs


【解决方案1】:

您的尝试即将实现。 ? 除了,你没有在产生它的名字后调用这个函数。

请再试一次:onClick = {() => handleIncrement()}

【讨论】:

  • 非常感谢龙。您的回答对我解决问题非常有帮助。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-06-26
  • 1970-01-01
  • 2022-01-05
  • 1970-01-01
  • 2020-02-11
相关资源
最近更新 更多