reactjs - React Hooks UseRef 问题
问题描述
我正在尝试使用 React 钩子。我对这段代码有疑问:
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 函数。这工作得很好,但我有一个问题将其更改为钩子代码。
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>
);
}
我该如何改造它?
解决方案
从文档中:
useRef
返回一个可变的 ref 对象,其.current
属性初始化为传递的参数 (initialValue)。返回的对象将在组件的整个生命周期内持续存在。
因此,您的代码应该是:
player.current.seekTo(30);
(可选检查是否player.current
设置)
useCallback
你可能也很有趣。
推荐阅读
- r - 如何在没有 row.names / 行号的情况下打印 tibble
- angular - Angular Library Project:如何将文件从一个辅助输入点导入另一个辅助入口点
- excel - 多个条件如果条件 - 根据前面的条件确定最高数字
- c# - EF Core 映射错误的属性名称
- xsd - xml:使用条件属性
- ffmpeg - 如何在 macos 上为 ffmpeg 启用 libx264
- google-cloud-platform - Gcloud 在单个命令中覆盖区域、区域和机器类型
- android - 使用flutter create创建android文件夹
- c# - c#将一行代码从列表写入数组
- javascript - 创建标签时如何防止使用onclick?