我想有一个创建表单,如果用户选择一个特定的美食,它会自动将指定的美食图像推送到React的表单中。我是新手。参见下面的useState setup:
useState:
const Create = (props) => {
const cuisine = ['Indian', 'American', 'Thai', 'Mexican', 'Spanish', 'Chinese'];
const [form, setForm] = useState({
cuisine: cuisine[0],
cuisineImg: "",
})
My onChange Handler:
const onChangeHandler = (e) => {
setForm({
...form,
[e.target.name]: e.target.value
})
}
然后这里是我的回报:
return (
<select name="cuisine" className="form-select my-3" onChange={onChangeHandler}>
<option disabled selected value> -- Select a Cuisine -- </option>
{
cuisine.map((cuisine, i) => {
return <option value={cuisine} key={i}> {cuisine}</option>
})
}
</select>)
}
当用户选择"印度"例如,我想要推送"indian .jpg"作为提交表单时键'cuisineImg'的值。(选中"American",然后推送"American.jpg",依此类推)。我要用selectHandler吗?如果有,是怎么做到的?
提前感谢您的帮助。
文件名只是一个字符串,所以如果图像的命名与数组值一致,你应该能够在setForm
:
const cuisine = e.target.value
const [form, setForm] = useState({
cuisine: cuisine,
cuisineImg: `${cuisine}.jpg`,
})
这只是连接字符串cuisine
和.jpg
的图像。在您的onChangeHandler
函数中,e.target.value
将等同于Indian
或American
等。