gpt4 book ai didi

javascript - 如何将选择的值从选择中获取到另一个组件?

转载 作者:行者123 更新时间:2023-12-04 07:14:22 25 4
gpt4 key购买 nike

我有这个 select 组件,它们的值取自 useEffect 数据。在这个组件中,我可以在控制台中看到从 select 中选择的值。

const SelectName = () => {
const [value, setValue] = useState(0);
const [names, setNames] = useState([]);
const handleChange = (e) => setValue(e.target.value);
useEffect(() => {
const unsubscribe = firestore
.collection("name")
.onSnapshot((snapshot) => {
const arr = [];
snapshot.forEach((doc) =>
arr.push({
...doc.data(),
id: doc.id,
})
);
setNames(arr);
});

return () => {
unsubscribe();
};
}, []);
// console.log(value);
return (
<div>
<FormControl fullWidth>
<InputLabel htmlFor="names">Names</InputLabel>
<Select onChange={handleChange} fullWidth>
{names &&
names.map((user) => (
<MenuItem
key={user.firstName + " " + user.lastName}
value={user.firstName + " " + user.lastName}
// defaultValue={}
>
{user.firstName + " " + user.lastName}
</MenuItem>
))}
</Select>
</FormControl>
</div>
);
};

export default SelectName;
我有这个其他组件和其他字段,我想在这里添加选择组件。但是,我无法以这种形式获取所选组件的值。我也会在这个组件中两次使用 select 组件;首先是第一个选择的名称和第二个选择的名称。并且可能存在用户可能输入不同名称的第一个和第二个 select 的情况。 .
我试过把 valueonChange在第一 select组件,但我在控制台中看不到所选值。我如何能够从选择中获取值?谢谢你。
  const [value, setValue] = useState("");
const handleChange = (e) => setValue(e.target.value);
console.log(value);



<form onSubmit={handleSubmit}>
//other fields
<Grid item>
//1st selected Name
<SelectName
value={value}
onChange={handleChange}
/>
</Grid>
<Grid item>
//2nd selected Name
<SelectName/>
</Grid>
<ButtonForm type="submit" fullWidth>
Submit
</ButtonForm>
</Grid>
</Grid>
</form>

最佳答案

你应该解构传递的 valueonChange Prop 并使用这些代替本地 value组件状态。

const SelectName = ({ value, onChange }) => {
const [names, setNames] = useState([]);

useEffect(() => {
const unsubscribe = firestore
.collection("name")
.onSnapshot((snapshot) => {
const arr = [];
snapshot.forEach((doc) =>
arr.push({
...doc.data(),
id: doc.id,
})
);
setNames(arr);
});

return () => {
unsubscribe();
};
}, []);

return (
<div>
<FormControl fullWidth>
<InputLabel htmlFor="names">Names</InputLabel>
<Select
value={value} // <-- pass value
onChange={onChange} // <-- pass change handler
fullWidth
>
{names &&
names.map((user) => (
<MenuItem
key={user.firstName + " " + user.lastName}
value={user.firstName + " " + user.lastName}
>
{user.firstName + " " + user.lastName}
</MenuItem>
))}
</Select>
</FormControl>
</div>
);
};
作为优化,并进一步概括,您可能还想将 firestore 逻辑分解到父级中,并将选项作为 Prop 传递。

关于javascript - 如何将选择的值从选择中获取到另一个组件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/68878643/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com