【发布时间】:2021-08-22 05:04:30
【问题描述】:
我有这个选择组件,它们的值取自 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 的不同名称。
我尝试将value 和onChange 放在第一个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>
【问题讨论】:
标签: javascript reactjs firebase google-cloud-firestore material-ui