【发布时间】:2021-05-22 22:58:59
【问题描述】:
我目前正在使用"typescript": "^3.7.5" 和"react-slick": "^0.25.2"。
我面临的问题是我无法将自动播放方法 slickPlay 和 slickPause 与新的 useRef 钩子和打字稿一起使用。
目标:能够通过播放/暂停按钮暂停自动播放和恢复自动播放。我的播放/暂停按钮将在分页点旁边。
我的代码:
import React, { useStateuseRef } from 'react';
const myComponent = () => {
const [autoPlayOn, setAutoPlayOn] = useState<boolean>(true);
const sliderRef = useRef<typeof Slider | null>(null);
<Slider
ref={sliderRef}
appendDots={(dots): JSX.Element => (
<MyButton
onClick={() => {
setAutoPlayOn(!autoPlayOn);
if (autoPlayOn) {
sliderRef.slickPlay();
} else {
sliderRef.slickPause();
}
}}
/>
)}
{...otherSettings}
>
}
我得到的类型错误是:
No overload matches this call.
Overload 1 of 2, '(props: Readonly<Settings>): Slider', gave the following error.
Type 'MutableRefObject<typeof Slider | null>' is not assignable to type 'string | ((instance: Slider | null) => void) | RefObject<Slider> | null | undefined'.
Type 'MutableRefObject<typeof Slider | null>' is not assignable to type 'RefObject<Slider>'.
Types of property 'current' are incompatible.
Type 'typeof Slider | null' is not assignable to type 'Slider | null'.
Type 'typeof Slider' is missing the following properties from type 'Slider': slickNext, slickPause, slickPlay, slickPrev, and 8 more.
Overload 2 of 2, '(props: Settings, context?: any): Slider', gave the following error.
Type 'MutableRefObject<typeof Slider | null>' is not assignable to type 'string | ((instance: Slider | null) => void) | RefObject<Slider> | null | undefined'.
Type 'MutableRefObject<typeof Slider | null>' is not assignable to type 'RefObject<Slider>'.
单击按钮时,我还遇到了另一个错误:
TypeError: sliderRef.slickPlay is not a function
我正在尝试调用精巧的方法slickPlay 和slickPause,但是我遇到了类型错误。我查看了https://github.com/akiran/react-slick/blob/master/examples/AutoPlayMethods.js 的示例,但是我仍然无法达到预期的结果。
将这些方法用于功能组件而不是基于类的组件让我感到困惑。添加打字稿层使其更具挑战性。
提前谢谢你。
【问题讨论】:
标签: reactjs typescript react-hooks ref react-slick