如果在 React Create Form 的下拉列表中选择了特定的 select 选项,则更新两个对象

Update two objects if specific select option is chosen in drop-down for React Create Form

我想要一个创建表单,如果用户选择特定的美食,它会自动将指定的美食图像推送到 React 中的表单中。我是新来的。请参阅下面的 useState 设置:

使用状态:

const Create = (props) => {
    const cuisine = ['Indian', 'American', 'Thai', 'Mexican', 'Spanish', 'Chinese'];
    
    const [form, setForm] = useState({
        cuisine: cuisine[0],
        cuisineImg: "",
})

我的 onChange 处理程序:

    const onChangeHandler = (e) => {
        setForm({
            ...form,
            [e.target.name]: e.target.value
        })
    }

那么这是我的 return:

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”时,我想在提交表单时将“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 将等同于 IndianAmerican