我对 React 很陌生,所以我还在学习很多东西。无论我做什么,onSelect 似乎都不起作用。我做了一个它应该调用的简单函数。您可以看出它是通过 console.log 调用的,但在浏览器中,当我查看控制台时,它什么也没做。
这是下拉菜单的代码:
import React,{useState} from 'react';
import SEPractices from "../dummydata/SEPractices"
const optionItems = SEPractices.map((SEPractice) =>
<option key={SEPractice.practice}>{SEPractice.practice}</option>
);
const Dropdown = () => {
const handleSelect=(e)=>{
console.log("Inside");
}
return (
<div>
<select onSelect={handleSelect}>
<option Default hidden>
Select an SE Practice
</option>
{optionItems}
</select>
</div>
)
}
export default Dropdown;
尝试使用
onChange
<select value={selectValue} onChange={handleSelect}>
<option value={""}>
Select an SE Practice
</option>
{optionItems}
</select>
并像这样处理Select:
const [selectValue, setValue] = useState("")
cosnt handleSelect = (e) => {
setValue(e.target.value);
}
<select value={selectValue} onChange={handleSelect}>
<option value="dummyData">
Select an SE Practice
</option>
{optionItems}
</select>
并且不要使用默认值和隐藏值,React 会处理默认值,为什么要在元素中指定
value={selectValue}
。
另外,我们需要将值传递给
<option>
,它会根据该值进行跟踪。