如何在Material-UI Data Grid按钮点击时弹出React组件?
解决Material-UI Data Grid点击按钮弹出弹窗组件的问题
问题说明
点击Material-UI Data Grid单元格中的Download按钮时,需要弹出ViewDownload.js组件作为弹窗,但当前代码在按钮点击事件中直接返回<ViewDownload />无法实现预期效果。
问题原因
React中,事件处理函数里直接返回组件不会触发渲染,必须将组件放在组件的JSX结构中,通过状态变量控制其显示/隐藏。
解决方案
通过React的useState管理弹窗的显示状态,点击按钮时更新状态,同时可传递当前行的数据给弹窗组件。修改后的完整代码如下:
import React, { useState } from 'react'; import { DataGrid } from '@mui/x-data-grid'; import Button from '@mui/material/Button'; import { Box, Typography } from '@mui/material'; import ViewDownload from './ViewDownload'; const columns = [ { field: 'id', headerName: 'SL. No', width: 70, headerClassName: 'super-app-theme--header' }, { field: 'status', headerName: 'PO Status', width: 80, headerClassName: 'super-app-theme--header' }, { field: 'action', headerName: 'Action', type: 'file', width: 120, headerClassName: 'super-app-theme--header', cellClassName: 'super-app-theme--cell', renderCell: (params) => ( <strong> <Button variant="contained" size="small" onClick={() => { // 设置弹窗显示状态,并传递当前行数据 setShowModal(true); setSelectedRow(params.row); }} > Download </Button> </strong> ) } ]; const rows = [ { id: 1, poNo: 'PO_CCTN_0822_001', poDate: '01/08/2022', from: '08/2022', to: '09/2022', state: 'TN', product: 'MLP', certificate: 'Document', quantity: '8000', status: 'PENDING', action: 'View/Download' } ]; const Document = () => { // 状态变量:控制弹窗显示/隐藏,存储选中行数据 const [showModal, setShowModal] = useState(false); const [selectedRow, setSelectedRow] = useState(null); return ( <> <Typography variant="h2" color="gray"> Documents </Typography> <Button variant="contained" sx={{ my: 3, background: 'gray', px: 3, py: 0 }}> Filter </Button> <Box display="flex" justifyContent="center" alignItems="center" minHeight="100vh" flexDirection="column" sx={{ mt: -18, mx: -14, '& .super-app-theme--header': { backgroundColor: 'gray', color: 'white' }, '& .super-app-theme--cell': { color: '#86C029', cursor: 'pointer' } }} > <Box sx={{ height: 300, width: { xs: '60%', sm: '65%', md: '80%' } }}> <DataGrid rows={rows} columns={columns} pageSize={5} rowsPerPageOptions={[5]} /> </Box> </Box> {/* 弹窗组件:根据状态控制显示,传递选中行数据 */} {showModal && <ViewDownload rowData={selectedRow} onClose={() => setShowModal(false)} />} </> ); }; export default Document;
关键修改点
- 引入
useState钩子,新增showModal控制弹窗显示,selectedRow存储当前点击行的数据 - 修改按钮的
onClick事件:更新状态显示弹窗,并记录当前行数据 - 在组件JSX末尾添加
ViewDownload组件,通过showModal状态控制渲染,同时传递关闭弹窗的方法和行数据(可根据ViewDownload组件的需求调整props)
如果你的ViewDownload组件本身没有关闭逻辑,建议在组件内部添加关闭按钮,并调用传入的onClose方法来更新父组件状态,隐藏弹窗。
内容的提问来源于stack exchange,提问作者Ashmita Singh
相关产品推荐
相关产品推荐

