React.js如何将map渲染的列表数据传递到Modal弹窗展示
React列表项数据传递到Modal弹窗实现方案
核心原因是当前逻辑只维护了弹窗的显示/隐藏布尔状态,没有存储点击触发时对应的行数据,补一个选中项状态就能解决,按以下步骤修改即可:
- 第一步:新增状态存储当前选中的视频数据
原有代码只声明了showModal控制弹窗开关,再加一个状态存当前要播放的视频对象,初始值设为null即可:const [showModal, setShowModal] = useState(false); const [currentVideo, setCurrentVideo] = useState(null); - 第二步:修改Watch按钮的点击事件
点击按钮触发弹窗打开的同时,把当前map遍历拿到的item存入currentVideo状态:<a onClick={() => { setCurrentVideo(item); setShowModal(true); }}> <FiPlay size="1.5rem" color="#009688" /> Watch </a> - 第三步:Modal组件绑定对应数据,关闭时重置状态
把Modal的标题、iframe的src属性绑定到currentVideo的对应字段,关闭弹窗时把currentVideo重置为null,避免下次打开弹窗短暂显示上一次的内容:<Modal show={showModal} onClose={() => { setShowModal(false); setCurrentVideo(null); }} title={currentVideo?.topic || "视频播放"} > <iframe src={currentVideo?.playUrl || ""} height="315" width="560" frameBorder="0" allowFullScreen /> </Modal>
注意:这里用可选链
?.做判空,避免弹窗初始化、currentVideo为null的时候读取属性报错,代码里的playUrl替换成你实际数据中存储iframe地址的字段名即可;另外React中DOM属性需要用小驼峰写法,原生的frameborder、allowfullscreen要改成frameBorder、allowFullScreen避免控制台警告。
修改后的完整参考代码:
// 组件顶部声明状态 const [showModal, setShowModal] = useState(false); const [currentVideo, setCurrentVideo] = useState(null); return ( <div> <Modal show={showModal} onClose={() => { setShowModal(false); setCurrentVideo(null); }} title={currentVideo?.topic || "视频播放"} > <iframe src={currentVideo?.playUrl || ""} height="315" width="560" frameBorder="0" allowFullScreen /> </Modal> <div className={styles.card}> <div className={styles.content}> <table> <thead> <tr> <td>#</td> <td>Topic</td> <td>View</td> </tr> </thead> <tbody> {VIDEOS_DATA.data.map((item) => ( <tr key={item.id}> <td>{item.id}</td> <td>{item.topic}</td> <td> <a onClick={() => { setCurrentVideo(item); setShowModal(true); }}> <FiPlay size="1.5rem" color="#009688" /> Watch </a> </td> </tr> ))} </tbody> </table> </div> </div> </div> )
如果你用的Modal组件默认会在关闭时卸载内部DOM内容,也可以省略currentVideo的重置逻辑,保险起见加上不会有异常。
内容的提问来源于stack exchange,提问作者kuiper0
相关产品推荐
相关产品推荐

