首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >使用React组件状态更改currentTime

使用React组件状态更改currentTime
EN

Stack Overflow用户
提问于 2018-09-29 23:57:46
回答 1查看 2.5K关注 0票数 2

这是一个link to the sandbox。我正在寻找操作<video>元素的currentTime的最佳方法。在我的沙箱中,我已经能够做到这一点,通过让按钮调用函数seek()来更改video的状态,这是对document.getElementById('video-player')的引用,如下所示。

代码语言:javascript
复制
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仍然没有改变。这里有什么想法吗?

EN

回答 1

Stack Overflow用户

发布于 2021-03-05 22:48:36

使用refs,而不是state来访问你的视频。

使用类:

代码语言:javascript
复制
constructor(props) {
  super(props);
  this.videoRef = React.createRef();
}

...

this.videoRef.current.currentTime = this.state.timestamp;

使用Hooks:

代码语言:javascript
复制
const videoRef = useRef(null);

...

videoRef.current.currentTime = timestamp;

并通过以下方式实施:

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/52570084

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档