Reactjs 如何在选择第一个组时显示首先选择的值?(有两个不同的选择)
我有一个JSON(今天在JS文件中,但稍后导入API): 我有2个“选择”,我按字母顺序将选项分组:Reactjs 如何在选择第一个组时显示首先选择的值?(有两个不同的选择),reactjs,Reactjs,我有一个JSON(今天在JS文件中,但稍后导入API): 我有2个“选择”,我按字母顺序将选项分组: import data from './data'; const SelectComponent = () => { const [group, setGroup] = useState({}); const optionSet = new Set(); return ( <> <Select onChange={(e) => setGr
import data from './data';
const SelectComponent = () => {
const [group, setGroup] = useState({});
const optionSet = new Set();
return (
<>
<Select onChange={(e) => setGroup(e.target.value)}>
{data
.filter((item) => {
if (!optionSet.has(item.group)) {
optionSet.add(item.group);
return true;
}
return false;
})
.sort((a, b) => a.group.localeCompare(b.group))
.map(({ id, group }) => (
<option key={id} value={group}>
{group}
</option>
))}
</Select>
<Select>
{data
.filter((item) => {
if (!optionSet.has(item.name)) {
optionSet.add(item.name);
return true;
}
return false;
})
.sort((a, b) => a.name.localeCompare(b.name))
.map(({ id, name }) => (
<option key={id} value={name}>
{name}
</option>
))}
</Select>
</>
);
}
export default SelectComponent;
从“/data”导入数据;
const SelectComponent=()=>{
const[group,setGroup]=useState({});
const optionstart=新集合();
返回(
setGroup(e.target.value)}>
{数据
.filter((项目)=>{
如果(!optionSet.has(item.group)){
OptiStart.add(项目组);
返回true;
}
返回false;
})
.sort((a,b)=>a.group.localeCompare(b.group))
.map({id,group})=>(
{group}
))}
{数据
.filter((项目)=>{
如果(!optionSet.has(item.name)){
OptiStart.add(项目名称);
返回true;
}
返回false;
})
.sort((a,b)=>a.name.localeCompare(b.name))
.map({id,name})=>(
{name}
))}
);
}
导出默认组件;
我想显示在第二个“选择”,只是第一组选择的选项
示例:如果我在第一次“选择”时选择了组AAA,我希望在第二次“选择”时显示选项:Foo和Bart
我必须使用包含“组”状态的第二个过滤器?我要写一些东西来促进讨论
const [firstChoices] = useState([1,2,3,4,5])
const [secondChoices, setSecondChoices] = useState([6,7])
const onSelect = e => {
const v = e.target.value
// based on the v
setSecondChoices(filtered(v))
}
return (
<>
<Select choices={firstChoices} onSelect={onSelect} />
<Select choices={secondChoices} />
</>
}
const[firstChoices]=useState([1,2,3,4,5])
常量[secondChoices,setSecondChoices]=useState([6,7])
const onSelect=e=>{
常数v=e.target.value
//基于v
设置秒选择(已过滤(v))
}
返回(
}
以上是高级代码,它也没有使用
Select
规范。但其思想是,在发送到底层渲染层之前,先整理逻辑,并将其存储在状态中。您的代码几乎可以正常工作。如果您想在选择第一个值后将group
用作持久值,那么这个组
必须显示在第二个选择
区域,尤其是在过滤器
上。当然,我们通常不会在渲染层中放置那么多实现。是的,我可能无法过滤“数据”,包括“组”状态。
const [firstChoices] = useState([1,2,3,4,5])
const [secondChoices, setSecondChoices] = useState([6,7])
const onSelect = e => {
const v = e.target.value
// based on the v
setSecondChoices(filtered(v))
}
return (
<>
<Select choices={firstChoices} onSelect={onSelect} />
<Select choices={secondChoices} />
</>
}