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

标签 reactjs

我刚刚开始使用 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/

相关文章:

javascript - 如何从 Draft.js json 渲染 React.js 内容

javascript - 进入和离开时reactjs背景颜色过渡

javascript - Jest 引用错误 'is not defined'

javascript - react Jest enzyme : testing callback of child component that calls another function first before calling the callback

reactjs - 无法从 react-admin 的编辑组件中删除删除按钮

ReactJS 通过 ref 渲染元素

css - React on Rails 错误导入 CSS

reactjs - 使用React.useMemo进行异步调用

node.js - 尝试发送文件时 FormData 发送空请求

reactjs - NextJS API 路由与 Firebase 云函数