我有一个系统,当输入特定值时,它会将选项添加到 Select 元素中.当该值更改时,它只会将更多选项附加到 Select 元素.如何删除旧选项?

示例代码:

const sections = ["Section 1", "Section 2"];
const sections2 = ["Section 3", "Section 4"];
const [selectedValue, setValue] = useState("");

if (selectedValue == "1") {
    sections?.forEach((option) => {
      const selectElement = document.getElementById(
        "section"
      ) as HTMLSelectElement;
      const optionElement = document.createElement("option");
      optionElement.value = option.sectionName;
      optionElement.text = option.sectionName;
      selectElement?.add(optionElement);
    });
} else {
    sections2?.forEach((option) => {
      const selectElement = document.getElementById(
        "section"
      ) as HTMLSelectElement;
      const optionElement = document.createElement("option");
      optionElement.value = option.sectionName;
      optionElement.text = option.sectionName;
      selectElement?.add(optionElement);
    });
}

return (
    <form>
        <select onChange={e => setValue(e)}>
            <option>Section List 1</option>
            <option>Section List 2</option>
        </select>
        <select id="section">
        </select>
    </form>
)

推荐答案

正如@dbs的 comments 中所提到的,您不应该在Reaction中进行直接的DOM操作.相反,请使用状态和呈现方法.以下是如何做到这一点.如果需要,请进行必要的更改:

const sections1 = ["Section 1", "Section 2"];
const sections2 = ["Section 3", "Section 4"];

const [selectedList, setSelectedList] = useState("");
const [sectionOptions, setSectionOptions] = useState([]);

useEffect(() => {
    if (selectedList === "Section List 1") {
        setSectionOptions(sections1);
    } else if (selectedList === "Section List 2") {
        setSectionOptions(sections2);
    } else {
        setSectionOptions([]);
    }
}, [selectedList]);

return (
    <form>
        <select value={selectedList} onChange={e => setSelectedList(e.target.value)}>
            <option value="">Select a section list</option>
            <option value="Section List 1">Section List 1</option>
            <option value="Section List 2">Section List 2</option>
        </select>
        <select id="section">
            {sectionOptions.map(option => (
                <option key={option} value={option}>{option}</option>
            ))}
        </select>
    </form>
);

Typescript相关问答推荐

类型脚本:类型是通用的,只能索引以供阅读.(2862)"

无法绑定ngModel.条件ngSwitchCase中的错误

如果字符串文字类型是泛型类型,则用反引号将该类型括起来会中断

打字类型保护递归判断

扩展参数必须具有元组类型或传递给REST参数

在另一个类型的函数中,编译器不会推断模板文字类型

AngularJS服务不会解析传入的Json响应到管道中的模型

为什么Typescript不能推断类型?

为什么&;(交集)运算符会删除不相交的属性?

如何在ANGLE中注册自定义验证器

返回嵌套props 的可变元组

跟踪深度路径时按条件提取嵌套类型

带投掷的收窄类型

使用Type脚本更新对象属性

如何为特定参数定义子路由?

使用来自API调用的JSON数据的Angular

如何扩展RxJS?

如何通过转换器类继承使用多态将对象从一种类型转换为另一种类型

打字:注解`是字符串`而不是`布尔`?

导航链接不触发自定义挂钩