这是一个link to the sandbox。我正在寻找操作<video>
元素的currentTime的最佳方法。在我的沙箱中,我已经能够做到这一点,通过让按钮调用函数seek()
来更改video
的状态,这是对document.getElementById('video-player')
的引用,如下所示。
export default class VideoPlayer extends React.Component {
constructor(props) {
super(props);
this.state = {
source: props.source,
timestamp: props.timestamp
};
}
componentDidMount() {
this.setState({ video: document.getElementById('video-player') })
}
componentDidUpdate(prevProps) {
if (this.props !== prevProps) {
this.setState(
{ timestamp: this.props.timestamp },
() => { this.seek() }
);
}
}
seek = () => {
console.log(this.state.timestamp)
//works
this.state.video.currentTime = 1;
//doesn't work
//this.state.video.currentTime = this.state.timestamp;
}
render() {
return (
<div>
<video
id='video-player'
height='200px'
src={this.state.source}
type='video/mp4'
controls>
</video>
{/* I don't want this button. I want skip from the outside */}
<button onClick={this.seek}>Skip Inside Component</button>
</div>
);
}
}
我不明白的是,我只能设法在组件内部更改currentTime,因为无论出于什么原因,我都不能将this.state.timestamp
赋给我的<video>
引用的currentTime (this.state.video.currentTime
)。
最终,组件应该接收Redux提供的props.timestamp
,在Redux的状态发生变化时调用<VideoPlayer />
内部的seek()
,并将视频的currentTime设置为this.state.timestamp
。
如果你们需要更多细节就告诉我。提前感谢!
编辑:上面的问题已经回答了,但我仍然有一个问题。不过,我共享并修复的沙箱在我的rails project中仍然不起作用。我有一种感觉,当点击App.js
中的三个按钮中的一个时,Redux中的状态会发生变化,并被<VideoPlayer>
成功接收。seek()
中的console.log确认了这一点,它将相应按钮的值返回到控制台。然而,视频的currentTime仍然没有改变。这里有什么想法吗?
发布于 2021-03-05 22:48:36
使用refs,而不是state来访问你的视频。
使用类:
constructor(props) {
super(props);
this.videoRef = React.createRef();
}
...
this.videoRef.current.currentTime = this.state.timestamp;
使用Hooks:
const videoRef = useRef(null);
...
videoRef.current.currentTime = timestamp;
并通过以下方式实施:
https://stackoverflow.com/questions/52570084
复制相似问题