React中基于Material-UI表格实现选中行弹窗/新标签页预览
Hey there! Let's get that preview functionality up and running for your selected rows. First, let's clean up a few parts of your existing code to make state management more reliable, then we'll implement two common preview options: a modal dialog and a new tab preview.
Step 1: Fix State Management for Selected Rows
Your current selectedList is a global variable, which can cause unexpected behavior when the component re-renders. Let's move it into the component's state instead for better control:
import React from 'react'; import { createMuiTheme, MuiThemeProvider } from '@material-ui/core/styles'; import MUIDataTable from "mui-datatables"; // We'll add more imports later for preview components export default class FaqsDataList extends React.Component { constructor(props) { super(props); this.state = { slide: "slideopen", inputhandle: "input--filled", value: "", createbot: "", faqList: [], response: [], selectedList: [], // Move selected rows into component state openPreviewDialog: false, // Controls modal visibility previewData: [] // Stores data to display in preview }; this.onChange = this.onChange.bind(this); } // Update options to use component state instead of global variable getOptions = () => ({ filterType: "checkbox", selectableRows: false, selectableRowsOnClick: true, onRowsSelect: (rowData, rowState) => { // Extract only selected row indices const selectedIndices = Object.keys(rowState).filter(key => rowState[key]); this.setState({ selectedList: selectedIndices }); } }); getMuiTheme = () => createMuiTheme({ overrides: { MuiPrivateSwitchBase: { root: { display: "block" } }, MUIDataTableToolbar: { root: { display: "none" } } } }); // ... rest of your existing methods (onChange, onFormSubmit) }
Step 2: Implement Preview Functionality
Pick the preview option that fits your use case, or add both for flexibility!
Option 1: Preview in a MUI Modal Dialog
First, import the necessary MUI components for the dialog:
import { Dialog, DialogTitle, DialogContent, Typography, Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper } from '@material-ui/core';
Update your submitList method to prepare preview data and open the dialog:
submitList = () => { // Map selected indices to actual row data const finaldata = this.state.selectedList.map(index => this.state.faqList[index] ); // Store preview data and trigger dialog open this.setState({ previewData: finaldata, openPreviewDialog: true }); }; // Close dialog when user clicks outside or close button closePreviewDialog = () => { this.setState({ openPreviewDialog: false }); };
Add the dialog component to your render method (place it inside the root <div>):
<Dialog open={this.state.openPreviewDialog} onClose={this.closePreviewDialog} maxWidth="md" fullWidth > <DialogTitle> <Typography variant="h6">Selected Rows Preview</Typography> </DialogTitle> <DialogContent> <TableContainer component={Paper}> <Table> <TableHead> <TableRow> {/* Render column headers from your columns array */} {columns.map(col => ( <TableCell key={col.name}>{col.label || col.name}</TableCell> ))} </TableRow> </TableHead> <TableBody> {this.state.previewData.map((row, rowIndex) => ( <TableRow key={rowIndex}> {/* Render each cell matching your column structure */} {columns.map(col => ( <TableCell key={col.name}>{row[col.name] || row[rowIndex]}</TableCell> ))} </TableRow> ))} </TableBody> </Table> </TableContainer> </DialogContent> </Dialog>
Option 2: Preview in a New Browser Tab
Add this method to generate a standalone HTML preview in a new tab:
previewInNewTab = () => { const finaldata = this.state.selectedList.map(index => this.state.faqList[index] ); // Build HTML content for the new tab const previewHtml = ` <!DOCTYPE html> <html> <head> <title>Selected FAQ Rows Preview</title> <style> body { font-family: Arial, sans-serif; margin: 2rem; } table { border-collapse: collapse; width: 100%; margin-top: 1rem; } th, td { border: 1px solid #ddd; padding: 0.8rem; text-align: left; } th { background-color: #f5f5f5; font-weight: bold; } h2 { color: #1976d2; } </style> </head> <body> <h2>Selected FAQ Rows Preview</h2> <table> <thead> <tr> ${columns.map(col => `<th>${col.label || col.name}</th>`).join('')} </tr> </thead> <tbody> ${finaldata.map(row => ` <tr> ${columns.map(col => `<td>${row[col.name] || row[index]}</td>`).join('')} </tr> `).join('')} </tbody> </table> </body> </html> `; // Open new tab and inject the HTML const newPreviewTab = window.open('', '_blank'); newPreviewTab.document.write(previewHtml); newPreviewTab.document.close(); };
Update your submit buttons to trigger either preview option:
<div className="col-md-2"> <button className="btn btn-primary btn-sm mr-2" onClick={() => this.submitList()}> Preview in Modal </button> <button className="btn btn-secondary btn-sm" onClick={() => this.previewInNewTab()}> Preview in New Tab </button> </div>
Final Notes
- Ensure your
columnsarray hasnameorlabelproperties so the preview tables can render correctly. Adjust the cell rendering logic if yourfaqListdata structure differs. - If you're using an older version of Material-UI, adjust imports to use
@material-ui/coreinstead of@mui/material.
内容的提问来源于stack exchange,提问作者sai chandan

