如何通过 React-slick useRef hook 和 typescript 使用自动播放方法

How to use AutoPlay methods with React-slick useRef hook and typescript

我目前正在使用 "typescript": "^3.7.5""react-slick": "^0.25.2"

我面临的问题是我无法通过新的 useRef 挂钩和打字稿使用自动播放方法 slickPlayslickPause

目标:能够使用 play/pause 按钮暂停自动播放和恢复自动播放。我的 play/pause 按钮将位于分页点旁边。

我的代码:

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

我正在尝试调用巧妙的方法 slickPlayslickPause,但是我 运行 遇到了类型错误。我已经查看了示例 https://github.com/akiran/react-slick/blob/master/examples/AutoPlayMethods.js,但是我仍然无法达到预期的结果。

让我困惑的是将这些方法用于功能组件而不是基于 class 的组件。添加打字稿层使其更具挑战性。

提前致谢。

先说第二部分:使用useRef时,必须参考.current才能得到实际实例。所以,你的电话看起来像:

sliderRef.current.slickPlay();

现在是第一部分。这一个,我愿意相信这可能会根据您使用的 Typescript/React/react-slick 版本而改变,但对我来说,如果我只使用 Typescript 就会停止抱怨:

const sliderRef = React.useRef<Slider>(null);

我能够通过检查 .current 而不是 sliderRef 来实现它。

const sliderElement = sliderRef.current;

if (sliderElement) {
  // do stuff
}

这个细微差别能够传递类型错误。

对于 useRef 声明,这一行有效(感谢@jnpdx 的帮助)

const sliderRef = React.useRef<Slider | null>(null);