React+TypeScript中如何将动态生成输入框的值存入单个变量
问题分析与解决方案
你的核心问题是每次输入只会保留当前单个输入框的值,无法整合所有输入框内容,原因有两个:
- 每次调用
appendWord时都初始化空字符串inputValue,导致新值只会替换旧值,无法累加 - 没有区分不同位置的输入框,不知道应该更新哪一部分内容
修正后的代码
import React, { useState, useRef, useEffect } from 'react' interface Props { word: string, setScoreHandler: (value: string) => void } const Input: React.FC<Props> = ({ word, setScoreHandler }) => { // 用数组保存每个输入框的值,长度与目标单词一致,初始为空字符串 const [inputValues, setInputValues] = useState<string[]>( Array(word.length).fill('') ) // 保存所有输入框的引用,用于自动聚焦 const inputRefs = useRef<(HTMLInputElement | null)[]>([]) const textArray = word.split('') const handleInputChange = (index: number, e: React.ChangeEvent<HTMLInputElement>) => { const newValue = e.target.value.slice(0, 1) // 确保只保留单个字符 // 复制原数组,修改对应索引的值(避免直接修改状态) const updatedValues = [...inputValues] updatedValues[index] = newValue setInputValues(updatedValues) // 将数组拼接成完整字符串,传递给父组件 const fullWord = updatedValues.join('') setScoreHandler(fullWord) // 自动聚焦下一个输入框(可选优化) if (newValue && index < textArray.length - 1) { inputRefs.current[index + 1]?.focus() } } const handleKeyDown = (index: number, e: React.KeyboardEvent<HTMLInputElement>) => { // 按退格键且当前输入框为空时,聚焦上一个输入框(可选优化) if (e.key === 'Backspace' && inputValues[index] === '' && index > 0) { inputRefs.current[index - 1]?.focus() } } const style: React.CSSProperties = { MozBoxShadow: "inset 0 0 10px #000000", WebkitBoxShadow: "inset 0 0 10px #000000", boxShadow: "inset 0 0 10px #000000", } useEffect(() => { // 组件挂载时自动聚焦第一个输入框 inputRefs.current[0]?.focus() }, []) return ( <> {textArray.map((_, index) => ( <input key={index} // 用索引作为key(因为每个输入框位置固定,不存在排序问题) ref={el => inputRefs.current[index] = el} style={style} type="text" maxLength="1" value={inputValues[index]} onChange={(e) => handleInputChange(index, e)} onKeyDown={(e) => handleKeyDown(index, e)} className='w-11 h-20 bg-walnut text-center text-3xl rounded-lg ml-3 shadow-inner-lg' /> ))} </> ) } export default Input
关键修改点说明
- 状态存储方式:从单个字符串改为数组,每个元素对应一个输入框的值,精准控制每个位置的内容
- 输入框标识:通过
index区分不同输入框,修改时只更新对应索引的元素 - 值绑定:给每个输入框加上
value={inputValues[index]},实现受控组件,确保状态与视图一致 - 用户体验优化:添加自动聚焦下一个输入框、退格键跳转上一个输入框的逻辑
- 类型修正:修正了
setScoreHandler的参数类型,避免any类型
内容的提问来源于stack exchange,提问作者schmulzcode
相关产品推荐
相关产品推荐

