1

我从 React 开始,我有一个问题。

我正在使用 Youtube API 来捕捉播放列表视频。使用 .map 方法,我在卡片中显示所有视频缩略图和标题。当我点击一张卡片时,我想通过“捕捉”我的数组的索引(在我的状态下)来启动视频(在 Reactplayer 中)。非常感谢您提供的答案和建议:)

下面是我的代码:

import React, { Component } from 'react'
import axios from 'axios';
import posed from 'react-pose';
import ReactPlayer from 'react-player';
import { Card, CardImg, Col, Row, CardTitle, Modal, ModalBody, ModalHeader } from 'reactstrap';
import './videos.css'

const Box = posed.div({
  hidden: { opacity: 0 },
  visible: { opacity: 1 }
});

class Videos extends Component {
  constructor () {
    super();
    this.state = {
      isVisible : true,
      videos: [],
      resultsDatas: "",
      nextPage: "",
      previousPage: "",
      videoId: "",
      search: "",
      playing: false,
      modal : false
    }
  }

componentDidMount() {
  axios.get('https://www.googleapis.com/youtube/v3/playlistItems?key=AIzaSyChOLdIP9GxDMPWjMmEnh6doR5Bdf1sGBk&playlistId=PL3-4jitn5YqtnR_mrYoz_Qb0z7frXZcW6&type=video&showinfo=0&iv_load_policy=3&part=snippet,id&order=date&maxResults=24')
  .then((result) => { 
    this.setState({
      videos: result.data.items,
      resultsDatas: result.data,
      nextPage: result.data.nextPageToken});
      console.log(this.state.videos);

      this.state.videos.map((item) => {
        if(item.snippet.title.length > 38) {
          return (item.snippet.title=`${item.snippet.title.slice(0,37)}... `);
        }
        })
    }
  )

  setTimeout(() => {this.setState({ isVisible: !this.state.isVisible }); 
  }, 400);

}


nextPage = () => {
  axios.get(`https://www.googleapis.com/youtube/v3/playlistItems?key=AIzaSyChOLdIP9GxDMPWjMmEnh6doR5Bdf1sGBk&playlistId=PL3-4jitn5YqtnR_mrYoz_Qb0z7frXZcW6&type=video&part=snippet,id&order=date&maxResults=24&pageToken=${this.state.nextPage}`)
  .then((result) => { 
    this.setState({
      nextPage: result.data.nextPageToken,
      previousPage: result.data.prevPageToken,
      videos: result.data.items,
      resultsDatas: result.data
    });
  })
}

previousPage = () => {
  axios.get(`https://www.googleapis.com/youtube/v3/playlistItems?key=AIzaSyChOLdIP9GxDMPWjMmEnh6doR5Bdf1sGBk&playlistId=PL3-4jitn5YqtnR_mrYoz_Qb0z7frXZcW6&type=video&part=snippet,id&order=date&maxResults=24&pageToken=${this.state.previousPage}`)
  .then((result) => { 
    this.setState({
      nextPage: result.data.nextPageToken,
      previousPage: result.data.prevPageToken,
      videos: result.data.items,
      resultsDatas: result.data});
  })
}

//For search function
inputChange = (event) => {
  this.setState({search: event.target.value })
}


playPause = (index) => {
  let element = document.getElementById(`play-pause${index}`);
  if (element.requestFullscreen) {
    this.setState({playing: !this.state.playing})
  }
}

toggleModal = () => {
  this.setState({
    modal: !this.state.modal
  });
}

  render() {
    let mapedVideos = this.state.videos.filter(
      (item) => {
        return item.snippet.title.toLowerCase().indexOf(this.state.search) !==-1;
      }
    );
  
    return (
      <div>

        <Box pose={this.state.isVisible ? 'hidden' : 'visible'}>
        <Row className="custom-videos-row mb-5">
          {mapedVideos.map((item, index) => {
            return (
              <Col className="custom-videos-col" lg="3" md="4" sm="6" key={index}> 
                <Card className="card-wrapper" onClick={() => {this.toggleModal()}}>
                  <CardImg className="video-thumbnail" src={item.snippet.thumbnails.medium.url} alt="thumb"></CardImg>
                    <CardTitle className="video-card-title pl-2"><img className="play-picto" src={process.env.PUBLIC_URL + '/images/play_L.png'} alt="play-picto"/>{item.snippet.title}
                      </CardTitle>
                </Card>
              </Col>
            );
            })}

            <Modal role="dialog" isOpen={this.state.modal} toggle={this.toggleModal}>
              <ModalHeader  className="custom-modal-header" toggle={this.toggleModal}>
                <img src={process.env.PUBLIC_URL + './images/logo.png'} alt="La Baule TV logo" className="LBTV-logo"></img>
                <span className="ml-2">La Baule</span></ModalHeader>
                <ModalBody>
                <ReactPlayer className="video-player"
                          url={'https://www.youtube.com/watch?v=T_IUcX17GXE&t=7s'}
                          playing= {true}
                          config={{
                            youtube: {
                              playerVars: { 
                                modestbranding: 1,
                                controls: 1,
                                rel: 0
                              }
                            }}}
                          />
                  </ModalBody>
              </Modal>
        </Row>
        </Box>
      </div>
    )
  }
}

export default Videos;

4

1 回答 1

1

要播放您点击的视频,您需要获取videoId特定视频的 并更改其中的 urlReactPlayer使其看起来像这样https://www.youtube.com/watch?v=xxxxxxxxxxx

创建一个名为onThumbnailClick或其他名称的函数,该函数是单击缩略图时要执行的函数。所以不要<Card className="card-wrapper" onClick={() => {this.toggleModal()}}>做类似 的事情<Card className="card-wrapper" onClick={() => {this.onClickThumbnail(index)}}>。(我们有之前使用的地图中的视频索引)

这个函数应该做的是用视频的url设置状态。我们将索引传递给函数。从 获取this.state.videosthis.state.videos[index]这将是点击的视频。

我们知道该特定视频的 videoId 处于视频状态。 this.state.videos[index].snippet.resourceId.videoId会给你videoId。使用该 videoId 设置状态,然后打开模式。

onClickThumbnail = (index) => {
  this.setState({
    clickedVideoId: this.state.videos[index].snippet.resourceId.videoId
  })
  this.toggleModal()
}

并将 ReactPlayer 网址更改为

url={`https://www.youtube.com/watch?v=${this.state.clickedVideoId}`}
于 2019-02-09T17:58:50.940 回答