javascript - 使用 React useState 统一输入值
问题描述
我在一个表单中有这三个 Quantity 输入。(其实可以更动态地添加,大概15个或更多。但为了简单起见,我说的是三个。)
| - | - | Quantity |
|---|---|----------|
| - | - | 3 |
| - | - | 4 |
| - | - | 5 |
我想在它们上方添加另一个输入以添加单个值并将它们设置为相同。
| - | - | Quantity |
|---|---|----------|
| - | - | 3 | <--- This input will set the same value for inputs below
|---|---|----------|
| - | - | 3 |
| - | - | 3 |
| - | - | 3 |
但是原来的三个 Quantity 输入仍然能够改变每个值。
这是我的尝试:
// form.tsx
...
const [value, setValue] = useState(0 || undefined)
const handleValue = (e: any) => setValue(e.target.value)
...
{/* Unify input to set the same value in inputs below */}
<input value={value} onChange={handleValue} />
{/* Without onChange, input will be set readOnly automatically, so I tried adding something */}
<input value={value} onChange={() => undefined} />
<input value={value} onChange={(e: any) => e.target.value} />
<input value={value} onChange={null} />
<input value={value} onChange={false} />
...
统一输入工作,它设置值。但我无法编辑下面的输入。我究竟做错了什么?
堆栈 - React:v16.13.1,TypeScript:v3.9.5
解决方案
问题似乎来自所有具有相同value
(value
状态)的输入。这为您提供了一种简单的方法来一次更新所有值,但如您所见,不允许单独更新它们。他们可以改变的唯一方法是在统一值setValue()
中的事件中调用if 。onChange
要更正此问题,您希望每个值都具有单独的状态。这可以通过在状态中存储一组值来完成,但为简单起见,我只是实现了额外的useState
钩子。
export const Form = () => {
const [unifyValue, setUnifyValue] = useState(0);
const [firstValue, setFirstValue] = useState(0);
const [secondValue, setSecondValue] = useState(0);
const [thirdValue, setThirdValue] = useState(0);
const handleUnifyValue = (e: any) => {
setUnifyValue(e.target.value);
setFirstValue(e.target.value);
setSecondValue(e.target.value);
setThirdValue(e.target.value);
}
const handleFirstValue = (e: any) => {
setFirstValue(e.target.value);
}
const handleSecondValue = (e: any) => {
setSecondValue(e.target.value);
}
const handleThirdValue = (e: any) => {
setThirdValue(e.target.value);
}
return (
<form>
{/* Unify input to set the same value in inputs below */}
<input value={unifyValue} onChange={handleUnifyValue} />
{/* Without onChange, input will be set readOnly automatically, so I tried adding something */}
<input value={firstValue} onChange={handleFirstValue} />
<input value={secondValue} onChange={handleSecondValue} />
<input value={thirdValue} onChange={handleThirdValue} />
</form>
)
}
如果我能让状态数组正常工作,我会用那个例子来更新它。这将允许超过 3 个输入,并减少对这么多useState
和handleXValue
行的需求。
推荐阅读
- amazon-web-services - DynamoDB contains() FilterExpression with query() 而不是 scan()
- vue.js - 如果每个页面的 route/url 都会改变但 url 后面的 shell 仍然相同,如何使 vue router.js 文件动态化?
- vba - 我想在嵌套 if-else 和使用 VBA 的 for 循环中不满足条件时弹出消息
- python - Azure ML Notebook:Tensorflow 未检测到 CUDA GPU
- flutter - Flutter 使用 Timer 进行后台工作,有什么缺点/问题吗?
- javascript - 如何将 Landbot 嵌入 Next.js 应用程序?
- shopify - Shopify Webhook 有效负载中缺少源信息
- android - Flutter 中的 AsyncSnapshot 始终为 null
- java - $ref 可能依赖于外部开放 API 规范?
- reactjs - 警告:道具类型失败:提供给“文本”的道具样式键“tintColor”无效