ReactJS中点击获取对象填充输入框实现内容编辑的问题咨询
功能实现方案
需调整的核心逻辑
- 用原有
current状态存储当前选中的问题ID,默认值设为null标识未选中任何问题 - 为每个渲染的问题Div绑定点击事件,点击时将对应问题的ID赋值给
current完成选中态同步 - 表单不再写死读取第一个问题的内容,改为根据
current匹配对应问题填充输入框 - 新增输入框内容变更事件,编辑时同步更新
questions数组中对应对象的属性,确保最终可以拿到所有修改后的全量数据
完整修改后代码
import { useState } from 'react'; export default function AddQuiz() { // current存储当前选中的问题ID,默认未选中 const [current, setCurrent] = useState(null); const [questions, setQuestions] = useState([]); function add_question() { const dumb = { id: `${Math.floor(100000 + Math.random() * 900000)}`, question: `${Math.random().toString(36).substr(2, 5)}`, anwser1: `${Math.random().toString(36).substr(2, 5)}`, anwser2: `${Math.random().toString(36).substr(2, 5)}`, anwser3: `${Math.random().toString(36).substr(2, 5)}`, anwser4: `${Math.random().toString(36).substr(2, 5)}`, }; const newQuestions = [...questions, dumb]; setQuestions(newQuestions); // 新增问题后自动选中新增的问题 setCurrent(dumb.id); } // 输入框内容变更同步到数组 const handleInputChange = (field, value) => { if (!current) return; setQuestions(prev => prev.map(item => { if (item.id === current) { return {...item, [field]: value} } return item; })) } // 获取当前选中的问题对象,未选中默认取第一个 const currentQuestion = questions.find(item => item.id === current) || questions[0]; return ( <> <pre> {questions.map((item) => ( // 绑定点击事件,加鼠标手势提示可点击 <div key={item.id} onClick={() => setCurrent(item.id)} style={{cursor: 'pointer', padding: '6px 0', borderBottom: '1px solid #eee'}} > question: {item.question} anwser1: {item.anwser1} anwser2: {item.anwser2} anwser3: {item.anwser3} anwser4: {item.anwser4} </div> ))} </pre> <button onClick={() => add_question()}>add dump question</button> <br /> <br /> <hr /> {questions.length !== 0 ? ( <form> <input type="text" value={currentQuestion.question} onChange={(e) => handleInputChange('question', e.target.value)} style={{display: 'block', margin: '8px 0'}} /> <input type="text" value={currentQuestion.anwser1} onChange={(e) => handleInputChange('anwser1', e.target.value)} style={{display: 'block', margin: '8px 0'}} /> <input type="text" value={currentQuestion.anwser2} onChange={(e) => handleInputChange('anwser2', e.target.value)} style={{display: 'block', margin: '8px 0'}} /> <input type="text" value={currentQuestion.anwser3} onChange={(e) => handleInputChange('anwser3', e.target.value)} style={{display: 'block', margin: '8px 0'}} /> <input type="text" value={currentQuestion.anwser4} onChange={(e) => handleInputChange('anwser4', e.target.value)} style={{display: 'block', margin: '8px 0'}} /> </form> ) : ( 'please add some question' )} </> ); }
内容的提问来源于stack exchange,提问作者jerek.orlin
相关产品推荐
相关产品推荐

