ReactJS使用Ajax根据第一个下拉列表选择的值填充下拉列表 [英] ReactJS populate dropdown list based on first dropdown list selected value with ajax
问题描述
因此,我遇到了有关这个类似问题的帖子, https://stackoverflow.com/a/48078627 答案是正确,但是它在javascript中,我该如何将其转换为如何处理这段代码的方式。
So I came across this post regarding this similar question, https://stackoverflow.com/a/48078627 the answer was correct but it is in javascript, how can I transform it into the way how react will handle this piece of code.
下面是javascript中的代码
Below is the code in 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开发的新手,如果能启发我,那将是很棒的这个问题。
I am new to React and web development as well, it would be great if you can enlighten me on this issue. Thanks a lot in advance.
推荐答案
我已经创建了 useState 和 useEffect
钩子链接到rel = nofollow noreferrer>样本实现所需的行为,但是还有很多其他方法可以实现。
I have created a sample using useState
and useEffect
hooks to achieve the desired behavior, but there are plenty other ways to do it.
开始时,我声明的是 选项
作为常量对象,其键
等于第一次选择的值。
At start, I am declaring options
as a constant object, with keys
equal to the values of the the first select.
编辑2:在作者请求之后,我更新了从远程服务器获取数据的示例,而不是使用常量。
EDIT 2: After author's request, I've updated my sample fetching data from remote server instead of using a constant.
然后使用 useState
处理第一个选择的用户选择。当此值更改时,我将查看数据状态,以获取适当的数据数组。
Then using useState
I handle the user selection of the first select. When this value change, I look into my data state, for the appropriate array of data.
我强烈建议您查看反应钩子了解更多详情。
I strongly recommend you to take a look to React hooks for more details.
编辑:我在提供的代码中添加了一些注释,逐步说明了该过程。
I've added some comments on the code provided, explaining step by step the process.
这篇关于ReactJS使用Ajax根据第一个下拉列表选择的值填充下拉列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!