繁体   English   中英

如何通过 React-slick useRef hook 和 typescript 使用 AutoPlay 方法

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

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

我面临的问题是我无法将自动播放方法slickPlayslickPause与新的useRef挂钩和 typescript 一起使用。

目标:能够通过播放/暂停按钮暂停自动播放和恢复自动播放。 我的播放/暂停按钮将在分页点旁边。

我的代码:

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但是我仍然无法达到预期的结果。

将这些方法用于功能组件而不是基于类的组件让我感到困惑。 添加 typescript 层使其更具挑战性。

先感谢您。

我将首先解决第二部分:使用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);

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM