【问题标题】:How can I handle the multiple select box in react in a single state如何在单一状态下处理多个选择框
【发布时间】:2021-10-01 12:26:03
【问题描述】:

我的初始状态

const [state,setState] = useState({
country : "",
nationality : "",
})

我的第一个选择标签:

<select> //select for country
<option>Nepal<option/>
<option>USA<option/>
</select>

我的第二个选择标签:

<select> //select for nationality 
<option>Nepali<option/>
<option>Ameracain<option/>
</select>

最后,我需要两个选择标签的所有选定值都处于单一状态。

const [state,setState] = useState({
    country : "Nepal",
    nationality : "Nepali",
    })

【问题讨论】:

  • 这可能会有所帮助。点击here

标签: html reactjs select


【解决方案1】:

here is a sample based on your example

import React, { useState } from "react";
import "./styles.css";

export default function App() {
  const [state, setState] = useState({
    country: "Nepal",
    nationality: "Nepali"
  });
  const handleChange = (e) => {
    const copy = { ...state };
    switch (e.target.name) {
      case "country":
        copy.country = e.target.value;
        break;
      case "nationality":
        copy.nationality = e.target.value;
        break;
      default:
        break;
    }
    setState(copy);
  };
  return (
    <div className="App">
      <select name="country" onChange={handleChange}>
        //select for country
        <option>Nepal</option>
        <option>USA</option>
      </select>
      My second select tag :
      <select name="nationality" onChange={handleChange}>
        //select for nationality
        <option>Nepali</option>
        <option>Ameracain</option>
      </select>
      {JSON.stringify(state)}
    </div>
  );
}

【讨论】:

  • 非常感谢,它可以工作,但是单句柄 onchange 可以工作吗??
  • 我需要你的小帮助.. 你愿意吗??
  • 如果可以,我会提供帮助。
  • 我们可以在谷歌见面会上联系吗??请
  • 对不起,我不能。你可以在这里发送。
猜你喜欢
  • 1970-01-01
  • 2018-03-18
  • 2020-03-24
  • 1970-01-01
  • 1970-01-01
  • 2021-03-26
  • 1970-01-01
  • 1970-01-01
  • 2019-02-08
相关资源
最近更新 更多