如何在select中动态添加项目? [英] How to add items in select dynamically in react?
问题描述
能否请您告诉我如何在react中动态添加select中的项目?
Could you please tell me How to add items in select dynamically in react ?
我正在从服务器获取响应(名称,标签等).例如,我只是模拟响应,两秒钟后就获取了响应.
I am getting response from server (name , label etc).For example I just mock my response and after two second I fetch that .
在我的示例中,我有两个选择框或下拉菜单.第一个下拉菜单具有值"one"和"two"(在json中作为选项提供).
In my example I have two select box or drop down .first dropdown have value "one" and "two"(which is given as options in json).
在json中还有一个选项dependentField
,它表示该字段依赖于另一个字段(提到的值是依赖的).在我的示例中,second
字段依赖于第一个字段.
In json there is one more option dependentField
it mean the field is dependent on another field (value mentioned is dependent).In my example second
field is dependent on first field.
因此,如果第一个选择框或下拉值ID为one
,则第二个选择或下拉字段的值将为["three", "four"]
.
So the value of second select or dropdown field will be ["three", "four"]
if first select box or dropdown value id one
.
因此,如果第一个选择框或下拉值ID为two
,则第二个选择或下拉字段的值将为["five", "six"]
.
So the value of second select or dropdown field will be ["five", "six"]
if first select box or dropdown value id two
.
所以我需要watch
如hook form
https://react-hook-form.com/get-started
我们可以动态添加选项
这是代码
https://codesandbox.io/s/stoic-benz-lxb8i
useEffect(() => {
console.log("====");
(async () => {
var a = await FETCH_API();
console.log("sssss");
setState(a);
console.log(a);
})();
}, []);
const getForm = () => {
try {
return state.map((i, index) => {
switch (i.type) {
case "text":
return (
<div key={index}>
<label>{i.label}</label>
<input type="text" ref={register()} name={i.name} />
</div>
);
case "select":
if (i.watch) {
watch(i.name, null);
}
return (
<div key={index}>
<label>{i.label}</label>
<select name={i.name} ref={register()}>
{i.options.map((i, idx) => {
return (
<option key={idx} value={i}>
{i}
</option>
);
})}
/
</select>
</div>
);
default:
return <div>ddd</div>;
}
});
return <div>ddd</div>;
} catch (e) {}
};
我不想做任何类似的骚扰行为
useEffect(()=>{
},[‘first’])
我们可以动态地观看或添加useeffect来动态地观看变化吗?
can we watch or add useeffect dynamically to watch change dynamically ?
任何更新
推荐答案
这是一个简单的两个选择.第一选择取决于第二个
this is a simpl two select. Where frist select depend on second
import React,{useState, useEffect} from "react"
const App = () => {
const [state,setState] = useState({
option1:["one","two"],
option2: []
})
useEffect(()=> {
(async () => {
var a = await FETCH_API();
console.log("sssss");
setState({
...state,
option2: a
});
console.log(a);
})();
},[state.option1])
return(
<div>
<select>
{
state.option1.map((i,idx)=>{
return(
<option key={idx} value={i}>
{i}
</option>
)
})
}
</select>
<select>
{
state.option2.map((i,idx)=>{
return(
<option key={idx} value={i}>
{i}
</option>
)
})
}
</select>
</div>
)
}
export default App
这篇关于如何在select中动态添加项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!