【发布时间】:2021-08-03 08:32:10
【问题描述】:
我正在使用 typescript、react 和 framer-motion。
我创建了一个 Counter 组件,其数量动态增加。
但是,我遇到了一些 ts 错误。
类型 '() => void' 不可分配给类型 'undefined'.ts(2322) 错误发生在①处。
错误无法调用可能是“未定义”的对象。ts(2722) 发生在位置②。
export const Index: React.FunctionComponent = () => {
return (
<Counter valueTo={30} totalDuration={2 + 0.5} />%
);
};
import { useEffect, useRef, useState } from 'react';
interface Props {
valueFrom: number;
valueTo: number;
totalDuration: number;
}
export const Counter: React.FunctionComponent<Props> = ({ valueFrom = 0, valueTo = 100, totalDuration = 1 }) => {
const [count, setCount] = useState(valueFrom);
useInterval(() => {
if (count < valueTo) {
setCount(count + 1);
}
}, (totalDuration / valueTo) * 1000);
return count;
};
const useInterval = (callback: () => void, delay: number) => {
const savedCallback = useRef();
// Remember the latest callback.
useEffect(() => {
// ①
savedCallback.current = callback;
}, [callback]);
// Set up the interval.
useEffect(() => {
function tick() {
// ②
savedCallback.current();
}
if (delay !== null) {
const id = setInterval(tick, delay);
return () => clearInterval(id);
}
}, [delay]);
};
【问题讨论】:
-
这能回答你的问题吗? How to use refs in React with Typescript
标签: reactjs typescript framer-motion