gpt4 book ai didi

reactjs - React.js + 视频元素 : set current play time from react props?

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

我刚刚开始使用 React,这是一个到目前为止我还没有找到好的解决方案的问题。问题是我想将标签中播放的视频设置为用户单击按钮时的位置。

我目前的解决方案如下:

componentDidUpdate(prevProps, prevState) {
console.log("Updating to timestamp: " + this.props.timestamp);
var timestamp = this.props.timestamp;
if (timestamp != prevProps.timestamp) {
React.findDOMNode(this.refs.theVideo).currentTime = timestamp;
}
}

问题是,这看起来真的很hacky。现在,我处于这种情况,用户可以单击同一按钮两次,但什么也不会发生,因此我正在考虑向组件添加更多状态,以确保这种情况正常工作。

这是正确的方法吗?到目前为止,React 中的一切似乎都非常合乎逻辑,但这感觉不太对劲。在这种情况下,您是否会将子级的方法公开给父级?

最佳答案

您在问题中提到了一个解决方案 - 您可以在子项上公开一种设置时间戳的方法。然而,这是一个非常命令式的 API,可能不太适合声明性的应用程序。

在最近的一个项目中,我使用声明式 API using componentWillReceiveProps 实现了类似的东西,与您自己的解决方案非常相似:

componentWillReceiveProps: function(props) {
if (this.props.playing !== props.playing) {
this.audio[props.playing ? "play" : "pause"]();
}

if (this.props.lastSeek !== props.lastSeek) {
var start = props.start,
offset = props.currentTime - start;
this.audio.currentTime = offset / 1000;
}
}

通过比较上次渲染时赋予组件的属性和本次渲染时赋予组件的属性,我们可以确定需要调整音频剪辑时间。

我认为最好的解决方案是创建一个特殊的 <Video>组件的唯一工作就是将这样的命令式 API 隐藏在声明式 API 后面;那么,您的应用程序不需要了解命令式 API。因此,在您的应用程序中,您可能会使用

render() {
// ...
<Video url={...} timestamp={this.props.timestamp} />
}

您可以了解有关此概念的更多信息 in this meetup talk: "Bridging Imperative APIs with Kinetophone" (7:04 左右)。

关于reactjs - React.js + 视频元素 : set current play time from react props?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/29908050/

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