[英]React Cascading Dropdowns (Dynamic)
The scenario is as follows: I want to make a reusable cascading dropdown component, however every video/article that I've seen on the topic just uses hard coded dependent dropdowns such as: Country => State => City.场景如下:我想制作一个可重复使用的级联下拉组件,但是我在该主题上看到的每个视频/文章都只使用硬编码的相关下拉列表,例如:Country => State => City。
However, for my situation it will not always be the same dependencies.但是,对于我的情况,它并不总是相同的依赖项。 How can I support custom dependency for cascading dropdowns?如何支持级联下拉菜单的自定义依赖项?
For a hardcoded example I would do something along the lines of having one useEffect for each of the options, and make the dependant options change when the parent changes.对于硬编码示例,我会按照为每个选项设置一个 useEffect 的方式做一些事情,并在父项更改时使相关选项发生更改。
I have an object example to iterate through of one page I am trying to accomplish this for:我有一个 object 示例来遍历我正在尝试完成的一页:
[
{
key: 0,
name: "State",
parentQuestion: null,
inputType: "Dropdown",
},
{
key: 1,
name: "Sublocation",
parentQuestion: "State",
inputType: "Dropdown",
},
{
key: 2,
name: "Operation",
parentQuestion: "Sublocation",
inputType: "Dropdown",
},
{
key: 3,
name: "Installment Number",
parentQuestion: "Operation",
inputType: "Dropdown",
},
{
key: 4,
name: "Upload Directory",
parentQuestion: null,
inputType: "File",
},
{
key: 5,
name: "Download Directory",
parentQuestion: null,
inputType: "Directory",
},
]
Is it possible to accomplish this?有可能做到这一点吗? Or must I hardcode the logic with different hooks for each page?或者我必须为每个页面使用不同的钩子对逻辑进行硬编码吗?
You can have the component
built passing the array data as props
, then iterating over each key on an element of the array, you have to build the select
s using map
.您可以构建将数组数据作为props
传递的component
,然后遍历数组元素上的每个键,您必须使用map
select
For the option values list you have to prepare another object such that对于选项值列表,您必须准备另一个 object 使得
optionList={country:[],state:[],city:[]}
You have to maintain an object
with selected options, and onchange of the select
s you have to modify the object
for selected options.您必须使用选定的选项维护object
,并且在更改select
时,您必须为选定的选项修改object
。
Edit Also onchange of select
s you have to modify the optionList
object, reducing the options array, for example编辑还 onchange of select
s 你必须修改optionList
object,减少选项数组,例如
if country is selected 'UK' then on the final object
selected you add the value final_object={country:'UK'}
and then in optionList
you have to reduce the options for corresponding state
and city
如果国家/地区选择“英国”,则在最终选择的object
上添加值final_object={country:'UK'}
然后在optionList
中,您必须减少相应state
和city
的选项
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.