首页 > 解决方案 > ReactJS 根据第一个下拉列表选择的值使用 ajax 填充下拉列表

问题描述

所以我遇到了关于这个类似问题的帖子,https://stackoverflow.com/a/48078627答案是正确的,但它是在 javascript 中,我怎样才能将它转换成 react 将如何处理这段代码的方式。

下面是javascript中的代码

<select id="sel" onchange="ChangeList()"> 
  <option value="">select</option> 
  <option value="I">Integer</option> 
  <option value="A">Alphabet</option> 
</select> 

<select id="type"></select> 

<script>
var IntandAlph = {};
IntandAlph['I'] = ['1', '2', '3','4','5','6','7','8','9','10'];
IntandAlph['A'] = ['A', 'B', 'C', 'D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'];

function ChangeList() {
    var selList = document.getElementById("sel");
    var typeList = document.getElementById("type");
    var seltype = selList.options[selList.selectedIndex].value;
    while (typeList.options.length) {
        typeList.remove(0);
    }
    var Num = IntandAlph[seltype];
    if (Num) {
        var i;
        for (i = 0; i < Num.length; i++) {
            var sel = new Option(Num[i], i);
            typeList.options.add(sel);
        }
    }
} 
</script>

</body>
</html>

我也是 React 和 Web 开发的新手,如果你能在这个问题上启发我,那就太好了。提前非常感谢。

标签: jsonajaxreactjsdropdown

解决方案


您可以在选择第一个下拉列表时value将第一个下拉列表的 存储到 中state。然后您options将第二个下拉列表的state.


推荐阅读