打字稿输入第三方自定义组件的参考(反应播放器)
Typescript typing a reference for third party custom components (react-player)
描述
我正在努力添加附加到此播放器组件的 useRef
的类型注释:react-player to get access to the seekTo
instance method as per the documentation demo source code。我似乎无法让该类型工作 - 我对打字稿有点陌生,可能会遇到这个错误,所以任何指针都会有所帮助!我查看了 react-player index.d.ts 并且可以看到该函数列在那里,只需要知道我应该如何编写它。
预期行为
可以访问播放器的实例方法。
错误
Property 'seekTo' does not exist on type 'MutableRefObject<ReactPlayer | null>'.ts(2339)
重现步骤
我制作了一个小的 codeSandbox - 基本上是试图模仿演示源添加一个 ref 以在范围类型输入上使用 seekTo
方法 onMouseUp
。
https://codesandbox.io/s/react-typescript-lqgvr?file=/src/index.tsx
谢谢!
关于您的代码的一些事情:
- 要访问 ref,请使用 ref.current 而不是 ref..
- ref可以为null,所以你必须检查它是否为null
- 使用事件的 currentTarget 来访问值而不是目标。
onMouseUp={(e) => {
if (player.current) {
player.current.seekTo(parseFloat(e.currentTarget.value));
}
}}
我也一直在纠结这个问题。
import { BaseReactPlayerProps } from 'react-player/base';
const MyPlayer = ({playerRef : BaseReactPlayerProps}) => {
// component code
if (playerRef) {
currentPlayerRef.seekTo(seconds, 'fraction');
}
}
我正在一个项目中使用 TS 和 React。我能够通过声明让一切正常工作:
const player = useRef<ReactPlayer>(null);
然后在我的 :
<ReactPlayer ref={player} />
所以每当我需要使用像 seekTo() 这样的函数时,它看起来像:
player?.current?.seekTo(seconds);
不需要使用:
import { BaseReactPlayerProps } from 'react-player/base';
描述
我正在努力添加附加到此播放器组件的 useRef
的类型注释:react-player to get access to the seekTo
instance method as per the documentation demo source code。我似乎无法让该类型工作 - 我对打字稿有点陌生,可能会遇到这个错误,所以任何指针都会有所帮助!我查看了 react-player index.d.ts 并且可以看到该函数列在那里,只需要知道我应该如何编写它。
预期行为
可以访问播放器的实例方法。
错误
Property 'seekTo' does not exist on type 'MutableRefObject<ReactPlayer | null>'.ts(2339)
重现步骤
我制作了一个小的 codeSandbox - 基本上是试图模仿演示源添加一个 ref 以在范围类型输入上使用 seekTo
方法 onMouseUp
。
https://codesandbox.io/s/react-typescript-lqgvr?file=/src/index.tsx
谢谢!
关于您的代码的一些事情:
- 要访问 ref,请使用 ref.current 而不是 ref..
- ref可以为null,所以你必须检查它是否为null
- 使用事件的 currentTarget 来访问值而不是目标。
onMouseUp={(e) => {
if (player.current) {
player.current.seekTo(parseFloat(e.currentTarget.value));
}
}}
我也一直在纠结这个问题。
import { BaseReactPlayerProps } from 'react-player/base';
const MyPlayer = ({playerRef : BaseReactPlayerProps}) => {
// component code
if (playerRef) {
currentPlayerRef.seekTo(seconds, 'fraction');
}
}
我正在一个项目中使用 TS 和 React。我能够通过声明让一切正常工作:
const player = useRef<ReactPlayer>(null);
然后在我的 :
<ReactPlayer ref={player} />
所以每当我需要使用像 seekTo() 这样的函数时,它看起来像:
player?.current?.seekTo(seconds);
不需要使用:
import { BaseReactPlayerProps } from 'react-player/base';