typescript 如何从select中的选定选项访问对象ID?

fcwjkofz  于 2023-01-06  发布在  TypeScript
关注(0)|答案(2)|浏览(124)

I have an object and the object.name is the select options. I need to get the object.id of the selected option in the select. Is it possible?
这是javascript,但是如果有一些方法可以在typescript中使用Enum或其他东西来完成,也可以!
我有这样一个目标:

const Months = {
  January: { id: 1, name: "January" },
  February: { id: 2, name: "February" },
  March: { id: 3, name: "March" },
  April: { id: 4, name: "April" },
  May: { id: 5, name: "May" },
  June: { id: 6, name: "June" },
  July: { id: 7, name: "July" },
  August: { id: 8, name: "August" },
  September: { id: 9, name: "September" },
  October: { id: 10, name: "October" },
  November: { id: 11, name: "November" },
  December: { id: 12, name: "December" },
};

和此App()fnc:

export default function App() {
  const [month, setMonth] = useState(Months.January.name);
  const [monthId, setMonthId] = useState(Months.January.id); // I tried this, but I don't know if it's possible

  const handleChange = (e) => {
    setMonth(e.target.value);
    // I tried to find something that return the Id for me in the 'e' but not success
  };

  return (
    <>
     <p>{month}</p>
     <p>{monthId}</p> // The id 1 is showed when I init the app, when I selected other option, it change to empty

     <select
      className={styles.selectMonth}
      defaultValue={month}
      onChange={handleChange}
     >
      {Object.keys(Months).map((key) => (
        <option key={key} value={key}>
          {Months[key].name}
        </option>
       ))}
     </select>
    <>
 );
}
rqqzpn5f

rqqzpn5f1#

您可以使用Months[e.target.value]访问month对象

nwwlzxa7

nwwlzxa72#

在select语句中你不会有你的id,因为你没有把id传递给实际的选项。基于你现在所拥有的,一个简单的解决方案如下:

const handleChange = (e) => {
   const m = e.target.value
    
   setMonth(m);
   setMonthId(Months[m].id)
};

相关问题