首页 > 解决方案 > React Hooks UseRef 问题

问题描述

我正在尝试使用 React 钩子。我对这段代码有疑问:

class VideoItem extends Component  {    
  handlePlayingStatus = () => {
    this.seekToPoint();
...
  }

  seekToPoint = () => {
    this.player.seekTo(30); // this worked - seek to f.ex. 30s
  }

  render() {
    const { playingStatus, videoId } = this.state;
    return (
      <Fragment>
        <ReactPlayer
          ref={player => { this.player = player; }}
          url="https://player.vimeo.com/video/318298217"
        />
        <button onClick={this.handlePlayingStatus}>Seek to</button>
      </Fragment>
    );
  }
}

所以我想从播放器那里获取 ref 并使用 seek 函数。这工作得很好,但我有一个问题将其更改为钩子代码。

const VideoItem = () => {    
  const player = useRef();

  const handlePlayingStatus = () => {
    seekToPoint();
...
  }

  const seekToPoint = () => {
    player.seekTo(30); // this does not work
  }

    return (
      <Fragment>
        <ReactPlayer
          ref={player}
          url="https://player.vimeo.com/video/318298217"
        />
        <button onClick={handlePlayingStatus}>Seek to</button>
      </Fragment>
    );
}

我该如何改造它?

标签: reactjs

解决方案


文档中:

useRef返回一个可变的 ref 对象,其.current属性初始化为传递的参数 (initialValue)。返回的对象将在组件的整个生命周期内持续存在。

因此,您的代码应该是:

player.current.seekTo(30);

(可选检查是否player.current设置)

useCallback你可能也很有趣。


推荐阅读