简体   繁体   English

当我动态添加新输入字段时,单选按钮和 Select 字段重置 [Reactjs]

[英]Radio button and Select field resets when I add a new input field dynamically [Reactjs]

I am trying to create a stack of input fields and I want to be able to add a new input field dynamically to the page.我正在尝试创建一堆输入字段,并且我希望能够向页面动态添加一个新的输入字段。 I am storing default fields in a state of array and when I want to add a new one I'm using setArr() to add a new one using spread operator.我将默认字段存储在数组的 state 中,当我想添加一个新字段时,我正在使用 setArr() 使用扩展运算符添加一个新字段。 The problem is that the values of radiobutton and select fields are resetting every time I create a new field.问题是每次我创建一个新字段时,radiobutton 和 select 字段的值都会重置。

在此处输入图像描述

import React, { useState } from "react";

export default function StackState() {
  const [arr, setArr] = useState([
    <input type='text' />,
    <input type='radio' />,
    <select>
      <option disabled selected>
        Disabled
      </option>
      <option>One</option>
      <option>Two</option>
    </select>,
  ]);

  const handleAdd = () => {
    setArr((e) => [<input type='text' />, ...e]);
  };

  return (
    <div>
      <div>{arr.map((e) => e)}</div>
      <button onClick={handleAdd}>Add Me</button>
    </div>
  );
}

You should store the value of option tag's disabled attribute and selected value in a different states and also on radio button value in a separate state and use onChange eventlistener on them, so that once there initial state is change call a function onChange and store the required values in that state.您应该将选项标记的禁用属性的值和选定值存储在不同的状态中,并且还存储在单独的 state 中的单选按钮值上,并在它们上使用 onChange 事件监听器,以便一旦有初始 state 更改调用 ZC1C425268E67A94F1 所需的 onChange 和存储state 中的值。

const [radioSelected,setRadioSelected] = useState(false);
const [optionDisabled,setOptionDisabled] = useState(true);
const [selectedOption,setSelectedOption] = useState("disabled");
const [arr, setArr] = useState([
<input type='text' />,
<input type='radio' checked={radioSelected} onChange={()=>setRadioSelected(!radioSelected)} />,
<select onChange={(e)=>setSelectedOption(e.target.value)}>
  <option disabled selected={selectedOption === "disabled" ? true : false} value="disabled">
    Disabled
  </option>
  <option selected={selectedOption === "one" ? true : false} value="one">One</option>
  <option selected={selectedOption === "two" ? true : false} value="two">Two</option>
</select>
]);

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM