如何用React+JS实现React Material UI学生表复杂条件查询?
Hey there! Let's walk through how to handle complex conditional queries for student data and render the results in a React Material UI table. I'll cover both the core JavaScript filtering logic and a complete React component implementation.
1. JavaScript 数据过滤逻辑
First, let's handle the data filtering part. Whether you're filtering data client-side or translating the logic to a backend query, the core condition is straightforward: include students where marks < 50 OR attendance > 75.
Client-Side Filtering (Frontend)
Here's a reusable function to filter an array of student objects:
// Sample student dataset const studentData = [ { id: 1, name: "Alice", marks: 45, attendance: 80, fees: 5000 }, { id: 2, name: "Bob", marks: 60, attendance: 70, fees: 4800 }, { id: 3, name: "Charlie", marks: 38, attendance: 65, fees: 5200 }, { id: 4, name: "Diana", marks: 75, attendance: 85, fees: 4900 }, ]; // Filter function implementing the complex condition const filterStudents = (students) => { return students.filter(student => { // Condition: marks < 50 OR attendance > 75 return student.marks < 50 || student.attendance > 75; }); }; // Usage example const filteredStudents = filterStudents(studentData); console.log(filteredStudents); // Outputs: Alice (marks 45), Diana (attendance 85)
Backend Query (SQL Example)
If you're fetching filtered data directly from a database, here's the corresponding SQL query:
SELECT id, name, marks, attendance, fees FROM students WHERE marks < 50 OR attendance > 75;
2. React + Material UI Table Implementation
Now let's integrate this logic into a React component using Material UI's table components. First, make sure you have the required dependencies installed:
npm install @mui/material @emotion/react @emotion/styled
Complete Component Code
import React, { useState, useEffect } from 'react'; import { Table, TableBody, TableCell, TableContainer, TableHead, TableRow, Paper, Typography, Box } from '@mui/material'; const StudentTable = () => { // State for raw student data (replace with API fetch in production) const [students, setStudents] = useState([ { id: 1, name: "Alice", marks: 45, attendance: 80, fees: 5000 }, { id: 2, name: "Bob", marks: 60, attendance: 70, fees: 4800 }, { id: 3, name: "Charlie", marks: 38, attendance: 65, fees: 5200 }, { id: 4, name: "Diana", marks: 75, attendance: 85, fees: 4900 }, { id: 5, name: "Eve", marks: 49, attendance: 74, fees: 5100 }, ]); const [filteredStudents, setFilteredStudents] = useState([]); // Apply filter whenever raw student data changes useEffect(() => { const applyComplexFilter = () => { const results = students.filter(student => { return student.marks < 50 || student.attendance > 75; }); setFilteredStudents(results); }; applyComplexFilter(); }, [students]); // Optional: Add dynamic condition controls // Uncomment below to let users adjust thresholds /* const [marksThreshold, setMarksThreshold] = useState(50); const [attendanceThreshold, setAttendanceThreshold] = useState(75); useEffect(() => { const results = students.filter(student => { return student.marks < marksThreshold || student.attendance > attendanceThreshold; }); setFilteredStudents(results); }, [students, marksThreshold, attendanceThreshold]); */ return ( <Box sx={{ padding: 3 }}> <Typography variant="h5" gutterBottom> Eligible Students </Typography> <Typography variant="body2" color="text.secondary" gutterBottom> Criteria: Marks < 50 OR Attendance > 75% </Typography> <TableContainer component={Paper}> <Table sx={{ minWidth: 650 }} aria-label="student table"> <TableHead> <TableRow> <TableCell>ID</TableCell> <TableCell>Name</TableCell> <TableCell align="right">Marks</TableCell> <TableCell align="right">Attendance (%)</TableCell> <TableCell align="right">Fees</TableCell> </TableRow> </TableHead> <TableBody> {filteredStudents.map((student) => ( <TableRow key={student.id} sx={{ '&:last-child td, &:last-child th': { border: 0 } }} > <TableCell component="th" scope="row"> {student.id} </TableCell> <TableCell>{student.name}</TableCell> <TableCell align="right">{student.marks}</TableCell> <TableCell align="right">{student.attendance}</TableCell> <TableCell align="right">{student.fees}</TableCell> </TableRow> ))} </TableBody> </Table> </TableContainer> </Box> ); }; export default StudentTable;
Key Notes About the Component
- State Management: We use
useStateto track both raw and filtered student data, anduseEffectto automatically re-run the filter whenever the raw data changes. - Material UI Integration: The table uses MUI's built-in components for a polished, responsive UI. We've added basic styling with MUI's
sxprop for padding and layout. - Dynamic Conditions: The commented section shows how to make the filter interactive—you can add input fields to let users adjust the marks/attendance thresholds, and the table will update in real-time.
Extensions for Production
- API Integration: Replace the hardcoded
studentsstate with data fetched from your backend usingfetchoraxios. - Advanced Filtering: For more complex conditions (nested AND/OR rules), you can build a condition object and evaluate it dynamically in the filter function.
- Table Enhancements: Add pagination with
TablePagination, sorting, or a search bar to make the table more user-friendly.
内容的提问来源于stack exchange,提问作者user6904754

