首页 > 解决方案 > 使用 React 组件状态更改 currentTime

问题描述

这是沙箱的链接。我正在寻找操纵<video>元素当前时间的最佳方法。在我的沙箱中,我已经能够通过一个按钮调用一个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的 currentTime 。<video>this.state.video.currentTime

最终组件应该接收props.timestamp由 Redux 提供的 ,每当 Redux 的状态发生变化时调用seek()内部<VideoPlayer />,并将视频的 currentTime 设置为this.state.timestamp

让我知道你们是否需要更多细节。提前致谢!

编辑:以上已经回答,但我仍然有一个问题。不过,我共享并刚刚修复的沙箱仍然无法在我的rails 项目中运行。我有一种感觉,它不会。当点击其中的三个按钮之一时App.js,Redux 中的状态会发生变化,并被<VideoPlayer>. 我的 console.log 确认了这一点,seek()其中将相应按钮的值返回到控制台。但是,视频的 currentTime 仍然没有改变。这里有什么想法吗?

标签: htmlreactjsreduxreact-reduxruby-on-rails-5

解决方案


mapStateToProps你的是state timestamp而不是state.timestampReducer

这应该有效:

const mapStateToProps = (state) => {
  return {
    timestamp: state
  }
};

推荐阅读