首页 > 解决方案 > 在 ReactJs 中将所选选项从一个选择添加到另一个选择

问题描述

我在 ReactJs 组件中有一个选择,其中包含一些选项,我希望将所选选项添加到另一个组件中的另一个选择中。例子:

const conponent1 = () => {
return <>
  <select>
    <option value="">Select a option</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option>
      <option value="3">Option 3</option>
    </select>
    <component2 />
  </>
} 

const component2 = () => {
return <>
  <select>
    <option value="">Select a option</option>\
    //It does not contain any options because one has not yet been chosen in the previous select.
    </select>
  </>
}

用户选择选项 2,因此必须将此选项添加到第二个组件的选择中。

const conponent1 = () => {
return <>
  <select>
    <option value="">Select a option</option>
      <option value="1">Option 1</option>
      <option value="2">Option 2</option> // Chosen option.
      <option value="3">Option 3</option>
    </select>
    <component2 />
  </>
} 

const component2 = () => {
return <>
  <select>
    <option value="">Select a option</option>\
    <option value="2">Option 2</option> // It was added because it was the chosen option.
    </select>
  </>
}

标签: javascriptreactjs

解决方案


https://codesandbox.io/s/nice-cartwright-6zulx?file=/src/index.js:0-69

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

const baseOptions = [
  {
    label: "option 1",
    value: "1"
  },
  {
    label: "option 2",
    value: "2"
  },
  {
    label: "option 3",
    value: "3"
  }
];

const Select = ({ options, onChange, value, disabledOptions = [] }) => (
  <select onChange={onChange} value={value}>
    <option disabled value="">
      select an option
    </option>
    {options.map((option, i) => (
      <option
        key={option.value}
        value={option.value}
        disabled={
          disabledOptions.findIndex((o) => o.value === option.value) !== -1
        }
      >
        {option.label}
      </option>
    ))}
  </select>
);

export default function App() {
  const [selectedOptions, setSelectedOptions] = useState([]);

  const [firstSelectValue, setFirstSelectValue] = useState("");
  const [secondSelectValue, setSecondSelectValue] = useState("");

  const handleFirstSelectChange = (e) => {
    const value = e.target.value;
    const option = baseOptions.find((o) => o.value === value);
    setSelectedOptions([...selectedOptions, option]);
    setFirstSelectValue(option.value);
  };

  const handleSecondSelectChange = (e) => {
    setSecondSelectValue(e.target.value);
  };
  return (
    <div className="App">
      <Select
        options={baseOptions}
        onChange={handleFirstSelectChange}
        value={firstSelectValue}
        disabledOptions={selectedOptions}
      />

      <Select
        options={selectedOptions}
        onChange={handleSecondSelectChange}
        value={secondSelectValue}
      />

      <div>Selected Value: {secondSelectValue}</div>
    </div>
  );
}

推荐阅读