【发布时间】: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