如何在 mouseEnter 上的 React 中播放视频

How can I play video in React on mouseEnter

我想在 mouseeEnter 上播放视频并在 mouseLeave 上暂停。每次我尝试这个我都会得到 TypeError: Cannot read 属性 'play' of undefined.

当我 console.log e.currentTarget 我收到正确的标签。

这是我目前所做的


import { MoviesList, MoviesListEl, Title, VideoWrap, MediaWrap, MovieDesc, MobilePreview } from "./styles"

export default class FetchRandomMovies extends React.Component {
  state = {
    loading: true,
    movies: []
  }

  async componentDidMount() {
    const url = "https://itunes.apple.com/us/rss/topmovies/limit=100/json"
    const response = await fetch(url)
    const data = await response.json()

    this.setState({ movies: data.feed.entry, loading: false })
  }

  getInitialState(e) {
    return {
      isPlaying: false
    }
  }
  mouseEnter = e => {
    this.setState({ isPlaying: true })
    console.log(e)
  }
  mouseLeave = e => {
    this.setState({ isPaused: false })
  }

  render() {
    if (this.state.loading) {
      return <div>loading...</div>
    }

    if (!this.state.movies.length) {
      return <div>didn't get movies</div>
    }
    return (
      <MoviesList>
        {this.state.movies.map(item => (
          <MoviesListEl key={item.title.label}>
            <Title>
              <span>{item.title.label}</span>
              <span>{item.category.attributes.term}</span>
            </Title>
            <MediaWrap>
              <img src={item["im:image"][2].label} alt="" />
              <VideoWrap>
                <video onMouseEnter={e => this.mouseEnter(e.currentTarget).play()} controls>
                  <source src={item.link[1].attributes.href} type="video/x-m4v" />
                </video>
              </VideoWrap>
            </MediaWrap>
            <MovieDesc>{item.summary.label}</MovieDesc>
            <MobilePreview href={item.link[1].attributes.href} />
          </MoviesListEl>
        ))}
      </MoviesList>
    )
  }
}

可能这一行有问题:

<video onMouseEnter={e => this.mouseEnter(e.currentTarget).play()} controls>

提前致谢

您调用 .play() 的值有误。您打算在 e.currentTarget 上调用 .play(),但这不是您的代码所说的。您的代码从 this.mouseEnter(e.currentTarget).

调用 void return 上的 .play()

您可以通过多种方式解决此问题,最简单的方法是在 mouseEnter 回调中调用 play()。因为这个回调应该接受事件,所以我们想传递它 e 而不是 e.currentTarget。但是由于 e 是默认参数,我们可以将函数提供给 onMouseEnter.

<video onMouseEnter={this.mouseEnter} controls>
mouseEnter = e => {
    e.currentTarget.play();
    this.setState({ isPlaying: true });
    console.log(e);
}