繁体   English   中英

如何捕获从下拉列表中选择的值?

[英]How to capture value selected from a dropdown list?

我有一个使用 React JS 创建的简单表单。 我有 2 个文本字段,类型和年份,以及一个下拉列表,即汽车。 使用来自 API 的值填充汽车下拉列表。 用户为前 2 个字段输入文本值,然后从下拉菜单中选择 car 的值并点击添加。 我有另一个帖子 API 捕获了这个值。 我可以存储和设置文本框的值,但对于下拉列表,汽车的值没有被捕获,我得到一个 null 值。 我如何存储汽车的价值,就像我为其他 2 个文本框所做的那样

import { useHistory } from "react-router-dom";
import axios from "axios";
import React,{useState,useEffect} from 'react';

function NewCar() {

  const [type, setType] = useState("");
  const [year, setYear] = useState("");
  const [car, setCar] = useState("");
  let history = useHistory();

  const [entries,setEntries]=useState([])
  
  useEffect(() => {
    fetchValues();
  }, [])

  useEffect(() => {
    console.log(entries)
  }, [entries])
  
  const fetchValues = async()=>{
    const response = await axios('http://localhost:8080/cars');
    setEntries(response.data)
  }

  const onSubmit = function (e) {
    e.preventDefault();
    axios
      .post("http://localhost:8080/update", {
        type,
        year,
        car
      })
      .then(() => history.push("/"));
  };

  return (
    <form onSubmit={onSubmit}>
    <table border="1">
      Type:{" "}
      <input
        name="type"
        value={type}
        onChange={(e) => setType(e.target.value)}
      />
      <br />
      Year:{" "}
      <textarea
        name="year"
        value={year}
        onChange={(e) => setYear(e.target.value)}
      ></textarea>{" "}
      <br />
      <label for="car">Car:</label>
        <select id="car" name="car">
          {entries.map((entry) => (
             <option value={entry.name}>{entry.name}</option>
          ))}
          name="car"
          value={car}
          onChange={(e) => setCar(e.target.value)}
       </select>
      <br />
    </table>
      <button>Add</button>
    </form>
  );
}

export default NewCar;


我相信您通过将属性放在 select 标记之外而在代码中犯了错误,它应该看起来像这样:

  <select
    id="car"
    name="car"
    value={car}
    onChange={(e) => setCar(e.target.value)}
  >
    {entries.map((entry) => (
      <option value={entry.name}>{entry.name}</option>
    ))}
  </select>

我有这个示例,您可以在其中获取 select 标记或下拉列表的值,希望您可以从中参考。

const [dataItem, setDataItem] = useState("");

  const data = [
    {
      name: "Ford",
      year: "1903",
    },
    {
      name: "Chevy",
      year: "1904",
    },
    {
      name: "Dodge",
      year: "1905",
    },
    {
      name: "Honda",
      year: "1906",
    },
    {
      name: "Toyota",
      year: "1907",
    },
  ];

  return (
    <>
      {dataItem}
      <select
        name="dataItem"
        value={dataItem}
        onChange={(e) => setDataItem(e.target.value)}
      >
        {data.map(({name}) => (
          <option value={name}>{name}</option>
        ))}
      </select>
    </>
  );

如果仍然出错,请让我知道并在下面写评论。

暂无
暂无

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

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