Javascript 反应物料界面自动填充文本输入

Javascript 反应物料界面自动填充文本输入,javascript,arrays,reactjs,material-ui,textfield,Javascript,Arrays,Reactjs,Material Ui,Textfield,我正在为我的项目使用MaterialUI和React。我有几个TextField,每个TextField旁边都有一个按钮,我想当一个按钮被点击时,它会分别得到其TextField的值,并将其值设置为其他TextField的输入,下面是 说明: 当你转到链接时,在每个文本字段旁边分别有3个文本字段和3个按钮 var defaultArray = Array(3).fill(""); var [valueList, setValueList] = useState(defau

我正在为我的项目使用MaterialUI和React。我有几个TextField,每个TextField旁边都有一个按钮,我想当一个按钮被点击时,它会分别得到其TextField的值,并将其值设置为其他TextField的输入,下面是

说明

当你转到链接时,在每个文本字段旁边分别有3个文本字段和3个按钮

 var defaultArray = Array(3).fill("");
 var [valueList, setValueList] = useState(defaultArray);
当您键入onChange事件时,它将为数组值列表中的项分别设置新值,但不会更新文本字段的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>
        );
      })}
{valueList.map((项目,索引)=>{
返回(
{
设newValueList=valueList;
newValueList[索引]=event.target.value;
setValueList(newValueList);
控制台日志(valueList);
}}
/>
{
设newValueList=Array(3).fill(valueList[index]);
setValueList(newValueList);
控制台日志(valueList);
}}
>
全部更新
);
})}

感谢您花时间帮助我,如果可能,您可以直接在codesandbox链接中修改它,祝您愉快

利用每个数组元素的
索引
来控制
文本字段
值。确保在更新状态时克隆
值列表
,以避免数组的直接变异

<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
/>
{

让newValueList=[…valueList];//您已经在valueList数组中添加了更改时的值。只需从该数组中获取值,并分别使用索引和更新。请检查下面的代码

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