React使用react-player实现点击按钮渲染对应YouTube游戏预告片求助
实现步骤
1. 修正电子游戏区域组件(VideoGameSection.jsx)
你当前的随机选游戏逻辑里的游戏名称是硬编码的,和单独存储的Games数据文件不同步,先修正这个问题,同时给GameEntry组件传递videoID字段:
import React from 'react'; import { Button, message } from 'antd'; import { Row, Col } from 'antd'; import GameEntry from '../GameEntry'; import Games from '../Games'; function VideoGameSection() { const chooseGame = () => { // 直接从Games数据取随机项,避免不同步 const randomIndex = Math.floor(Math.random() * Games.length); const randomGame = Games[randomIndex]; message.info(`你本次要游玩的游戏是:${randomGame.title}。`); }; return ( <div id="video-game" className="block bgGray"> <div className="container-fluid"> <div className="titleHolder"> <h2>电子游戏</h2> <p>当前收录的游戏列表</p> <div className="site-button-ghost-wrapper"> <Button className="gameButton" type="primary" danger ghost onClick={chooseGame} > 帮我随机选 </Button> </div> </div> <Row gutter={[16, 24]}> {Games.map((videogame, i) => ( <Col span={8} key={i}> <GameEntry id={i} title={videogame.title} imgURL={videogame.imgURL} description={videogame.console} // 传递预告片ID给子组件 videoID={videogame.videoID} /> </Col> ))} </Row> </div> </div> ); } export default VideoGameSection;
2. 修改游戏条目组件(GameEntry.jsx)
接收父组件传递的videoID,再传给YoutubeSection组件,同时增加模态框关闭时重置播放状态的逻辑,避免关闭后声音继续播放:
import React, { useState } from 'react'; import { Card, Button, Modal } from 'antd'; import YoutubeSection from './Home/YoutubeSection'; const { Meta } = Card; function GameEntry(props) { const [isModalVisible, setIsModalVisible] = useState(false); const showModal = () => { setIsModalVisible(true); }; const handleClose = () => { setIsModalVisible(false); }; const handleCancel = () => { setIsModalVisible(false); }; return ( <div> <Card className="gameCard" hoverable cover={<img className="cardImg" alt={props.title} src={props.imgURL} />} > <div className="cardTitle"> <Meta title={props.title} description={props.description} /> </div> <> <Button className="trailerButton" type="primary" block style={{ color: '#fff', borderColor: '#fff', backgroundColor: '#e6544f', }} onClick={showModal} > 查看预告片 </Button> <Modal title={props.title} width={'725px'} visible={isModalVisible} onOk={handleClose} onCancel={handleCancel} // 销毁模态框内的子组件,关闭即停止播放 destroyOnClose > {/* 传递当前游戏的videoID给视频组件 */} <YoutubeSection videoID={props.videoID} /> </Modal> </> </Card> </div> ); } export default GameEntry;
3. 修改YouTube视频组件(YoutubeSection.jsx)
接收videoID参数,拼接成完整的YouTube播放地址传给react-player:
import React from 'react'; import ReactPlayer from 'react-player'; function YoutubeSection(props) { // 拼接完整YouTube播放地址 const videoUrl = `https://www.youtube.com/watch?v=${props.videoID}`; return ( <div className="container-fluid"> <ReactPlayer url={videoUrl} muted={false} playing={true} controls={true} // 适配容器宽度 width="100%" /> </div> ); } export default YoutubeSection;
额外说明
- 你游戏数据里的videoID字段如果已经带了时间戳后缀(比如示例里的
SEpWlFfpEkU&t=7s)也可以正常拼接,不需要额外处理 - 如果后续要支持国内视频平台,只需要修改YoutubeSection里的url拼接逻辑即可
内容的提问来源于stack exchange,提问作者N.O
相关产品推荐
相关产品推荐

