gpt4 book ai didi

reactjs - React Hooks UseRef 问题

转载 作者:行者123 更新时间:2023-12-04 14:48:04 25 4
gpt4 key购买 nike

我正在尝试使用 React 钩子(Hook)。我对这段代码有疑问:

class VideoItem extends Component  {    
handlePlayingStatus = () => {
this.seekToPoint();
...
}

seekToPoint = () => {
this.player.seekTo(30); // this worked - seek to f.ex. 30s
}

render() {
const { playingStatus, videoId } = this.state;
return (
<Fragment>
<ReactPlayer
ref={player => { this.player = player; }}
url="https://player.vimeo.com/video/318298217"
/>
<button onClick={this.handlePlayingStatus}>Seek to</button>
</Fragment>
);
}
}

所以我想从播放器获取 ref 并在其上使用 seek 函数。这工作得很好,但我有一个问题将其更改为钩子(Hook)代码。

const VideoItem = () => {    
const player = useRef();

const handlePlayingStatus = () => {
seekToPoint();
...
}

const seekToPoint = () => {
player.seekTo(30); // this does not work
}

return (
<Fragment>
<ReactPlayer
ref={player}
url="https://player.vimeo.com/video/318298217"
/>
<button onClick={handlePlayingStatus}>Seek to</button>
</Fragment>
);
}

如何改造?

最佳答案

来自 documentation :

useRef returns a mutable ref object whose .current property is initialized to the passed argument (initialValue). The returned object will persist for the full lifetime of the component.

因此您的代码应该是:

player.current.seekTo(30);

(可选检查是否设置了player.current)

useCallback你可能也会感兴趣。

关于reactjs - React Hooks UseRef 问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55032269/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com