在React中设置单选按钮值 [英] Set radio button value in React

查看:48
本文介绍了在React中设置单选按钮值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在使用带有单选按钮的表单制作一个简单的react应用.

I am making a simple react app with form that has radio buttons.

这里有一个可用的默认数据,

Here there is a default data available like,

const defaultData = [{ ContactMode: 3 }, { ContactMode: 2 }, { ContactMode: 2 }];

要求:

->需要迭代此 defaultData 并分配它们各自的 ContactMode 模式,如在每一行中选中的那样.

-> Need to iterate this defaultData and assign their respective ContactMode mode as checked in each row.

有效代码段:

const { useState } = React;

const App = () => {
  const [formValue, setFormValue] = useState({
    ContactMode: 1
  });

  const defaultData = [{ ContactMode: 3 }, { ContactMode: 2 }, { ContactMode: 2 }];

  const handleInputChange = (e, index) => {
    const { name, value } = event.target;
    setFormValue({
      ...formValue,
      [name]: value
    });
  };

  const submitData = () => {
    console.log(formValue);
  };

  return (
    <div>
      <form>
        {defaultData.map((item, index) => {
          return (<React.Fragment>
            <label> Contact Mode </label>
            <input
              type="radio"
              name="ContactMode"
              checked={item.ContactMode == 1}
              value={1}
              onChange={(event) => handleInputChange(index, event)}
            />{" "}
            Email
            <input
              type="radio"
              name="ContactMode"
              checked={item.ContactMode == 2}
              value={2}
              onChange={(event) => handleInputChange(index, event)}
            />{" "}
            Text
            <input
              type="radio"
              name="ContactMode"
              checked={item.ContactMode == 3}
              value={3}
              onChange={(event) => handleInputChange(index, event)}
            />{" "}
            Both
            <br />
            <br />
            <button type="button">
               Save
             </button>
            <br />
            <br />
            <br />
          </React.Fragment>);
        })}
      </form>
    </div>
  );
};

ReactDOM.render(<App />, document.getElementById("root"));

<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.11.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.11.0/umd/react-dom.production.min.js"></script>
<div id="root"></div>

预期输出:

Contact Mode  Email Text Both (Checked)

Contact Mode  Email Text(Checked) Both

Contact Mode  Email Text(Checked) Both

注意:我无法修改名称属性 name ="ContactMode" .保存按钮,该特定行将被保存.每行应具有 name ="ContactMode" ..

Note: I can't modify the name attribute name="ContactMode".. Reason is I also have individual save button each row and on click of that save button that particular row will gets saved.. And each row should have name="ContactMode" ..

由于我的问题不清楚我要实现的目标,因此我将在此处提供整个代码.

As my question is not clear in what I am trying to achieve, I am going to give the entire code here.

-> ,我有一个Stepper表单,其中第2步"是就业"部分,默认情况下,我有要设置为表单的值,

-> I have a stepper form in which Step 2 is employment section and by default I have the values to set into the form,

const dynamicData = [
  {
    EmploymentID: 1,
    companyName: 'Company One',
    designation: 'Designation One',
    ContactMode: 3,
  },
  {
    EmploymentID: 2,
    companyName: 'Company two',
    designation: 'Designation One',
    ContactMode: 2,
  },
];

-> 里面的 useEffect 钩子中,我将表单值设置为

-> Inside useEffecthook I set the form value like,

  React.useEffect(() => {
    setExpanded(0);
    setValue((prev) => {
      const companyDetails = [...dynamicData];
      return { ...prev, companyDetails };
    });
  }, []);

此处正确绑定了带有输入框的表单值,但未选中单选按钮值.

Here the form values with input boxes are binded properly but the radio button value doesn't gets checked.

-> ,有两个可用数据,但默认情况下第一个将展开,而第二个将通过单击下面的 Expand 按钮打开.第一个.

-> There are two data's available but the first one will be expanded by default and whereas the second one will gets opened on click of the Expand button below the first one.

-> 在单击 save 按钮时,该特定对象( inputField )将被控制台记录(仅测试)以及修改后的数据.

-> On click of the save button, that particular object (inputField) will be console logged (testing only) along with modified data..

在这里,问题是如果我们修改数据,则说明一切正常,但仅通过单选按钮检查的属性无法对项目进行检查..(检查的指示不起作用)..

Here the ISSUE is if we modify the data then things are working fine but the radio checked attribute alone not making the item checked.. (Checked indication is not working)..

请转到下面给出的代码和框中的第2步,以查看问题.要查看第二项,请单击展开按钮.

Please go to step 2 in the below given codesandbox to see the issue.. To see the second item, click on the expand button..

请帮助我在每行中设置默认的单选按钮值.

Please kindly help me to set default radio button value in each row.

推荐答案

在您的沙箱中,我可以使单选按钮起作用

In your sandbox I was able to get the radio buttons to work by

  1. 为每个映射的无线电组提供唯一的名称
  2. 更新更改处理程序以唯一地处理 ContactMode 属性.

更新无线电组以使用当前的映射索引,以使它们在所有映射组中都是唯一的.

Update the radio groups to use the current mapped index in order to make them unique among all mapped groups.

<div className="form-group col-sm-4">
  <label className="inline-flex items-center mr-6">
    <input
      type="radio"
      className="form-radio border-black"
      name={`ContactMode-${index}`} // <-- append index to name
      value={1}
      checked={inputField.ContactMode === 1} // <-- use strict "==="
      onChange={(event) => handleInputChange(index, event)}
    />
    <span className="ml-2">Email</span>
  </label>
</div>
<div className="form-group col-sm-4">
  <label className="inline-flex items-center mr-6">
    <input
      type="radio"
      className="form-radio border-black"
      name={`ContactMode-${index}`}
      value={2}
      checked={inputField.ContactMode === 2}
      onChange={(event) => handleInputChange(index, event)}
    />
    <span className="ml-2">Text</span>
  </label>
</div>
<div className="form-group col-sm-4">
  <label className="inline-flex items-center mr-6">
    <input
      type="radio"
      className="form-radio border-black"
      name={`ContactMode-${index}`}
      value={3}
      checked={inputField.ContactMode === 3}
      onChange={(event) => handleInputChange(index, event)}
    />
    <span className="ml-2">Both</span>
  </label>
</div>

handleInputChange 中添加一个案例以专门处理 ContactMode .

In the handleInputChange add a case to handle ContactMode specially.

const handleInputChange = (index, event) => {
  const { name, value } = event.target;
  if (name === 'designation' && !isLettersOnly(value)) {
    return;
  }

  if (name.startsWith('ContactMode')) { // <-- check name prefix
    setValue((prev) => ({
      ...prev,
      companyDetails: prev.companyDetails.map((detail, i) =>
        i === index
          ? {
              ...detail,
              ContactMode: Number(value), // <-- store back under correct key, as number for string equality check
            }
          : detail,
      ),
    }));
    return; // <-- return early so other state update is skipped!
  }

  setValue((prev) => {
    const companyDetails = prev.companyDetails.map((v, i) => {
      if (i !== index) {
        return v;
      }

      return { ...v, [name]: value };
    });

    return { ...prev, companyDetails };
  });
};

这篇关于在React中设置单选按钮值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆