javascript - 如何在 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 构建的。
解决方案
但我面临的问题是,如果选项的值相同,则选项不会被重置。
我假设这意味着您希望每次更改单选按钮时下拉菜单重置为第一个索引。现在,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
推荐阅读
- python - n 个变量之间的相等性
- c# - ASP.Net 无法将字节值添加到我的 SQL Server
- python - 从同级目录导入功能(__init__ 文件不起作用)
- tensorflow - Pre_trained model work well on ResNet, InceptionNet but unable to run on VGG16 and VGG19
- firebase - 更新firebase实时数据库xamarin表单中的单个数据
- c - 推广 For 和 Malloc 的大小 C
- r - 如何将颜色图例添加到具有不同几何图层的 ggplot?
- javascript - 在 vuex 中运行以下代码时未定义“mapGetters”
- python - 使用 dropna() 后获取 MultiIndex 级别 0 的名称
- c# - C# -> 如何从文本框中实时读取和打印值