ReactJS中如何通过循环在表格中添加文本输入框并获取选中行的特定值
实现核心逻辑
- 给每条行数据绑定唯一标识(优先用API返回的业务ID,不要用循环索引,避免行顺序调整后取值匹配错乱)
- 初始化和行数据对应的存储结构(对象/数组都可,推荐用对象,键为行的唯一ID),用来存储每一行输入框的用户输入值
- 输入框的输入事件触发时,同步将值更新到存储结构中对应行ID的位置
- 提交时遍历存储结构,和原行数据做匹配即可拿到每行的完整数据
原生JavaScript实现示例
// 假设API返回的源数据格式,每条带唯一id const tableData = [ { id: 1, name: '条目1', field2: '值1', field3: '值2' }, { id: 2, name: '条目2', field2: '值3', field3: '值4' }, // 更多数据... ] // 初始化存储输入值的对象,key为行id const inputValues = {} const tableBody = document.querySelector('tbody') // 渲染表格 tableData.forEach(row => { const tr = document.createElement('tr') // 渲染原有3列数据+最后一列输入框 tr.innerHTML = ` <td>${row.name}</td> <td>${row.field2}</td> <td>${row.field3}</td> <td><input type="text" data-row-id="${row.id}" class="row-input"></td> ` tableBody.appendChild(tr) }) // 监听输入事件同步存储值 document.querySelectorAll('.row-input').forEach(input => { input.addEventListener('input', e => { const rowId = e.target.dataset.rowId inputValues[rowId] = e.target.value.trim() }) }) // 提交时获取所有行的输入值 function handleSubmit() { // 合并原数据和输入值,得到完整的提交数据 const submitData = tableData.map(row => ({ ...row, userInput: inputValues[row.id] || '' })) // 后续处理submitData即可 console.log('提交数据:', submitData) }
Vue3 实现示例
<template> <table> <thead> <tr> <th>列1</th> <th>列2</th> <th>列3</th> <th>用户输入</th> </tr> </thead> <tbody> <tr v-for="row in tableData" :key="row.id"> <td>{{ row.name }}</td> <td>{{ row.field2 }}</td> <td>{{ row.field3 }}</td> <td><input v-model="inputValues[row.id]" type="text"></td> </tr> </tbody> </table> <button @click="handleSubmit">提交表格</button> </template> <script setup> import { ref, onMounted } from 'vue' const tableData = ref([]) const inputValues = ref({}) // 调用API获取表格数据 onMounted(async () => { const res = await fetch('/your/api/path') tableData.value = await res.json() // 初始化输入值存储,避免v-model绑定告警 tableData.value.forEach(row => { inputValues.value[row.id] = '' }) }) const handleSubmit = () => { const submitData = tableData.value.map(row => ({ ...row, userInput: inputValues.value[row.id] })) // 提交submitData到后端 console.log(submitData) } </script>
React 实现示例
import { useState, useEffect } from 'react' function TablePage() { const [tableData, setTableData] = useState([]) const [inputValues, setInputValues] = useState({}) // 获取表格数据 useEffect(() => { fetch('/your/api/path') .then(res => res.json()) .then(data => { setTableData(data) // 初始化输入值 const initInput = {} data.forEach(row => initInput[row.id] = '') setInputValues(initInput) }) }, []) const handleInputChange = (rowId, value) => { setInputValues(prev => ({ ...prev, [rowId]: value })) } const handleSubmit = () => { const submitData = tableData.map(row => ({ ...row, userInput: inputValues[row.id] })) console.log('提交数据:', submitData) } return ( <div> <table> <thead> <tr> <th>列1</th> <th>列2</th> <th>列3</th> <th>用户输入</th> </tr> </thead> <tbody> {tableData.map(row => ( <tr key={row.id}> <td>{row.name}</td> <td>{row.field2}</td> <td>{row.field3}</td> <td> <input type="text" value={inputValues[row.id]} onChange={e => handleInputChange(row.id, e.target.value)} /> </td> </tr> ))} </tbody> </table> <button onClick={handleSubmit}>提交表格</button> </div> ) }
注意事项
- 禁止使用循环索引作为输入框的唯一关联标识,如果你有行删除、排序等交互,索引会发生变化,导致输入值和行匹配错乱
- 如果需要给输入框设置默认值,初始化
inputValues时直接赋值即可,不需要额外适配 - 如果需要做单行列输入校验,可在输入事件触发时同步校验对应行的输入值,错误信息也按行ID存储,渲染时直接对应展示
内容的提问来源于stack exchange,提问作者code
相关产品推荐
相关产品推荐

