【问题标题】:React Material Ui Autofill Text inputReact Material Ui 自动填充文本输入
【发布时间】:2021-02-02 01:52:45
【问题描述】:

我正在为我的项目使用 Material UI 和 React。我有几个TextField,每个旁边都有一个按钮,我希望当一个按钮被点击时,它会分别获取其TextField的值并将其值设置为其他TextField的输入,这里是codesandbox link

说明

当您转到链接时,您将分别在每个 TextField 旁边有 3 个 TextField 和 3 个按钮,

 var defaultArray = Array(3).fill("");
 var [valueList, setValueList] = useState(defaultArray);

当你键入 onChange 事件时,会为数组 valueList 中的 item 设置相应的新值,但它不会更新 TextField 的 defaultValue,请让它也更新 defaultValue

 {valueList.map((item, index) => {
        return (
          <div key={index}>
            <TextField
              id="standard-basic"
              label="label"
              defaultValue={valueList[index]}
              onChange={(event) => {
                let newValueList = valueList;
                newValueList[index] = event.target.value;
                setValueList(newValueList);
                console.log(valueList);
              }}
            />
            <Button
              variant="contained"
              color="primary"
              onClick={() => {
                let newValueList = Array(3).fill(valueList[index]);
                setValueList(newValueList);
                console.log(valueList);
              }}
            >
              Update All
            </Button>
          </div>
        );
      })}

感谢您花时间帮助我,如果可以的话,您可以直接在codeandbox链接中修改,祝您有美好的一天

【问题讨论】:

    标签: javascript arrays reactjs material-ui textfield


    【解决方案1】:

    利用每个数组元素的index来控制TextFieldvalue。确保在更新状态时克隆 valueList 以避免数组的直接突变

    <TextField
      id="standard-basic"
      label="label"
      defaultValue={valueList[index]}
      onChange={(event) => {
        let newValueList = [...valueList]; // <-- pay attention to usage of spread syntax
        newValueList[index] = event.target.value;
        setValueList(newValueList);
        console.log(valueList);
      }}
      value={valueList[index]} // <-- we can transform this to a controlled component
    />
    

    【讨论】:

      【解决方案2】:

      您已经在 valueList 数组中添加了更改值。只需从该数组中获取值并使用索引并分别更新它。请检查下面的代码。

      <Button
                    variant="contained"
                    color="primary"
                    onClick={() => {
                      let newValueList = valueList;
                      newValueList[index] = valueList[index];
                      setValueList(newValueList);
                      console.log(newValueList);
                    }}
                  >
                    Update All
                  </Button>
      

      【讨论】:

        猜你喜欢
        • 2020-10-18
        • 2018-03-29
        • 1970-01-01
        • 2021-07-14
        • 2021-12-13
        • 2018-09-20
        • 2020-11-04
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多