首页 > 解决方案 > 如何在 ReactJS 中更改单选按钮时重置选定的下拉列表

问题描述

我有单选按钮,然后是选择下拉菜单。每个单选按钮都与一组与其相关的选项相关联。每当单选按钮更改时,下拉菜单中的选项也应该更改。但我面临的问题是,如果选项的值相同,则选项不会被重置。

这是数据

const data = [
    {
      name: "option1",
      info: [1, 2, 3, 4, 5]
    },
    {
      name: "option2",
      info: [1, 2, 3, 4, 5]
    },
    {
      name: "option3",
      info: [6, 7, 8, 9, 10]
    }
  ];

我在这里创建了一个示例链接。链接(https://codesandbox.io/s/react-hello-world-forked-rnwe2?file=/src/index.js

这是基于 ReactJS 构建的。

标签: javascripthtmlreactjscomponents

解决方案


但我面临的问题是,如果选项的值相同,则选项不会被重置。

我假设这意味着您希望每次更改单选按钮时下拉菜单重置为第一个索引。现在,DOM 控制着当前选择的内容,因此如果选择了下拉列表中的第 3 项,则 DOM 将存储第 3 项的值已选择。React 只是在您更改选项时更改每个项目中的值(请参阅和解),它实际上并没有select在 DOM 中重新创建节点。

为此,我建议select控制元素,例如

import React, { useState } from "react";
import ReactDOM from "react-dom";

function App() {
  const [current, setCurrent] = useState(1);
  const [selected, setSelected] = useState("");
  const data = [
    {
      name: "option1",
      info: [1, 2, 3, 4, 5]
    },
    {
      name: "option2",
      info: [1, 2, 3, 4, 5]
    },
    {
      name: "option3",
      info: [6, 7, 8, 9, 10]
    }
  ];

  function handleChange(id) {
    setCurrent(id);
    setSelected("");
  }

  function handleSelected(event) {
    setSelected(event.target.value);
  }

  return (
    <div>
      {data.map((item, key) => {
        return (
          <label key={key}>
            <input
              type="radio"
              name="test"
              checked={key === current ? true : false}
              onChange={(e) => handleChange(key)}
              value={key}
            />
            {item.name}
          </label>
        );
      })}
      <hr />
      <br />
      <select
        value={selected}
        style={{ width: "100px", padding: 10 }}
        onChange={handleSelected}
      >
        {data[current].info.map((item, key) => {
          return <option>{item}</option>;
        })}
      </select>
    </div>
  );
}

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

https://codesandbox.io/s/react-hello-world-forked-d9cuh?file=/src/index.js


推荐阅读