React实现学生成绩表可编辑单元格的动态更新功能
React 实现点击单元格切换输入框的可编辑学生评分表
整个功能不需要依赖第三方组件,靠React原生状态就能实现,核心逻辑非常简单:
- 用两个状态配合完成交互:一个存全量的学生评分数据,另一个记录当前正在编辑的单元格位置(匹配到对应行、对应字段时才显示输入框)
- 渲染逻辑判断:非编辑状态的单元格渲染普通文本,点击时把位置信息存到编辑状态里,自动切换成输入框;输入框失焦、按下回车时清空编辑位置,切回普通文本展示
完整可运行实现代码
import { useState } from 'react'; function EditableScoreTable() { // 存所有学生的评分数据,可根据实际需求增减字段 const [studentScores, setStudentScores] = useState([ { id: 1, name: '张三', math: 85, english: 92, science: 78 }, { id: 2, name: '李四', math: 90, english: 88, science: 95 }, { id: 3, name: '王五', math: 76, english: 81, science: 89 }, ]); // 记录当前编辑的目标位置,无编辑时为null // 格式:{ studentId: 对应学生id, field: 需要编辑的字段名 } const [editingTarget, setEditingTarget] = useState(null); // 单元格值更新逻辑 const updateCellValue = (studentId, field, newValue) => { // 必须做不可变拷贝,不能直接修改原state const newData = studentScores.map(student => { if (student.id === studentId) { return { ...student, [field]: Number(newValue) }; } return student; }); setStudentScores(newData); }; return ( <table style={{ borderCollapse: 'collapse', width: '80%', margin: '2rem auto' }}> <thead> <tr> <th style={headerStyle}>学生姓名</th> <th style={headerStyle}>数学</th> <th style={headerStyle}>英语</th> <th style={headerStyle}>科学</th> </tr> </thead> <tbody> {studentScores.map(student => ( <tr key={student.id}> <td style={cellStyle}>{student.name}</td> {/* 遍历所有可编辑的成绩字段 */} {['math', 'english', 'science'].map(field => { // 判断当前单元格是否处于编辑状态 const isCurrentEditing = editingTarget?.studentId === student.id && editingTarget?.field === field; return ( <td key={field} style={{...cellStyle, cursor: 'pointer'}} onClick={() => !isCurrentEditing && setEditingTarget({ studentId: student.id, field })} > {isCurrentEditing ? ( <input autoFocus type="number" value={student[field]} style={{ width: '90%', padding: '0.3rem' }} onChange={(e) => updateCellValue(student.id, field, e.target.value)} // 失焦/按回车就退出编辑 onBlur={() => setEditingTarget(null)} onKeyDown={(e) => e.key === 'Enter' && setEditingTarget(null)} /> ) : ( student[field] )} </td> ) })} </tr> ))} </tbody> </table> ); } const headerStyle = { border: '1px solid #ddd', padding: '0.8rem', background: '#f5f5f5' }; const cellStyle = { border: '1px solid #ddd', padding: '0.8rem', textAlign: 'center' }; export default EditableScoreTable;
新手容易踩的坑
- 很多新手刚做这个功能时,会惯性给每个单元格单独绑一个“是否正在编辑”的布尔状态,最后很容易出现点一个单元格,好几个单元格同时弹出输入框的bug。其实根本没必要:全局只存当前正在编辑的那一个单元格的位置,其他单元格全部渲染普通文本就行,逻辑简单还不容易出问题。
- 更新状态时必须做数据拷贝,不能直接修改原数组、原对象的属性,不然React监听不到状态变化,输入内容后界面不会动态更新。
- 给输入框加上
autoFocus属性,切换成输入框时自动聚焦,不用用户额外点一下,和你参考图的交互效果完全一致。 - 同时支持失焦、回车两种退出编辑的操作,符合日常表单的使用习惯。
内容的提问来源于stack exchange,提问作者bikram muduli
相关产品推荐
相关产品推荐

