如何在React和TypeScript中创建输入框值与标签的数组?
解决方案
1. 先定义类型(TypeScript规范)
为了让数组元素结构更严谨,先定义一个Food类型约束:
type Food = { value: number; label: string; };
2. 实现表单提交逻辑
在组件内编写提交函数,直接基于输入状态生成目标格式的数组:
import { useState } from 'react'; const FoodForm = () => { const [field1, setField1] = useState<number>(0); const [field2, setField2] = useState<number>(0); // 若后续需要复用数组,就定义状态保存;仅临时使用可删除该行 const [foods, setFoods] = useState<Food[]>([]); const handleSubmit = (e: React.FormEvent) => { e.preventDefault(); // 生成符合要求的数组 const newFoods: Food[] = [ { value: field1, label: 'Amount of apples' }, { value: field2, label: 'Amount of bananas' } ]; // 需要复用数组时,更新状态 setFoods(newFoods); // 直接使用数组,比如你需要的map操作 const foodLabels = newFoods.map(food => food.label); console.log(foodLabels); // 输出 ["Amount of apples", "Amount of bananas"] }; return ( <form onSubmit={handleSubmit}> <label>Amount of apples <input placeholder="Add apples" type="number" value={field1} onChange={(e) => setField1(parseInt(e.target.value, 10) || 0)} /> </label> <label>Amount of bananas <input placeholder="Add bananas" type="number" value={field2} onChange={(e) => setField2(parseInt(e.target.value, 10) || 0)} /> </label> <button type="submit">Count</button> </form> ); }; export default FoodForm;
3. 是否需要将数组保存到状态?
- 无需保存:如果数组只是提交时临时使用(比如直接传给后端接口、临时计算),不用存状态,在
handleSubmit里生成后直接使用即可。 - 需要保存:如果后续组件要基于数组渲染内容(比如展示食物数量列表),或者其他函数需要访问数组的最新值,就需要把它存在
useState里。
内容的提问来源于stack exchange,提问作者azrac
相关产品推荐
相关产品推荐

