javascript - 在 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>
</>
}
解决方案
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>
);
}
推荐阅读
- vulkan - 更新顶点缓冲区的小部分
- python - Python的排序功能问题
- python - 在 python / pandas 中使用打印的加权统计数据分组
- sed - 使用 grep/sed 提取字符串之间的字符串
- python - 如何从三角形的图像中找到三角形的角度
- javascript - Vue.js 在 websocket onmessage 事件中更新 html
- c - 读取后 FIFO 管道内容包含错误的字符
- angular - Angular chartjs:如何将表中的变量 *ngfor 转换为折线图
- ios - UITableview单元格的左右约束
- c# - DataTable.Select ("Complete").Count<> 没有给出正确的总数