首页 > 解决方案 > 使用 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

标签: javascriptreactjstypescript

解决方案


问题似乎来自所有具有相同valuevalue状态)的输入。这为您提供了一种简单的方法来一次更新所有值,但如您所见,不允许单独更新它们。他们可以改变的唯一方法是在统一值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 个输入,并减少对这么多useStatehandleXValue行的需求。


推荐阅读