React点击按钮无法显示iframe问题求助
问题分析与解决办法
你的问题出在showurl函数的写法上——直接在函数里写JSX代码不会让React把它渲染到页面上,React需要通过状态来控制元素的显示和内容。下面是修改后的完整代码,同时兼顾后续从数据库获取链接的需求:
import React, { useState } from "react"; import { useLocation, useNavigate } from "react-router-dom"; import Blog from "../../components/dashboard/Blog"; import Course from "./Course"; import EmbedsPage from "./EmbedsPage"; function Coursedetail(props) { const location = useLocation(); const navigate = useNavigate(); console.log(location.state.id) // 用状态控制iframe显示/隐藏,以及存储YouTube嵌入链接 const [isIframeVisible, setIsIframeVisible] = useState(false); const [youtubeEmbedUrl, setYoutubeEmbedUrl] = useState(""); const image = location.state.image; const title = location.state.title; const discription = location.state.description; const showurl = () => { // 这里后续可以替换成从数据库获取的嵌入链接 // 如果数据库里是watch格式的链接(比如https://www.youtube.com/watch?v=RGKi6LSPDLU),需要转成embed格式 const fetchedUrl = "https://www.youtube.com/embed/RGKi6LSPDLU"; setYoutubeEmbedUrl(fetchedUrl); setIsIframeVisible(true); console.log("hii"); } return ( <> <div className="card"> <h5 className="card-header">Featured</h5> <div className="card-body"> <img src={image} alt="" style={{ width: "50%" }} ></img> <h5 className="card-title">{title}</h5> <p className="card-text">{discription}</p> <button className="btn btn-primary" onClick={showurl}> Watch Now </button> <button href="" className="btn btn-primary" style={{ margin: "15px" }} > Save PDF </button> {/* 根据状态渲染iframe */} {isIframeVisible && ( <div className="embed-responsive embed-responsive-16by9" style={{ marginTop: "20px" }}> <iframe width="560" className="embed-responsive-item" height="315" src={youtubeEmbedUrl} title="YouTube video player" frameBorder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture; web-share" allowFullScreen ></iframe> </div> )} </div> </div> </> ); } export default Coursedetail;
关键修改点:
- 新增
useState钩子管理iframe的显示状态和嵌入链接,这是React控制元素渲染的标准方式。 showurl函数不再直接写JSX,而是修改状态触发组件重新渲染,从而显示iframe。- 在DOM结构里用条件渲染
{isIframeVisible && ...}决定是否显示iframe,保证只有点击按钮后才会渲染。 - 预留了从数据库获取链接的位置,后续把
fetchedUrl替换成你的数据库查询结果即可(注意要把YouTube的watch链接转换成embed格式,否则iframe无法正常加载)。
内容的提问来源于stack exchange,提问作者Ritik Choudhary
相关产品推荐
相关产品推荐

