React Bootstrap DropdownButton取值报错:Uncaught TypeError: evt is null
问题出在React Bootstrap的DropdownButton的onSelect回调参数机制上:它的第一个参数不是事件对象,而是选中的Dropdown.Item的value属性值,你之前沿用了Select组件的事件处理逻辑,所以会出现evt is null的错误。
修改步骤:
- 调整
handleLangChange函数的参数,直接接收选中的语言值,而非事件对象 - 移除
evt.target.value的写法,直接使用传入的参数 - 可选优化:将DropdownButton的title改为动态显示当前选中的语言(国旗+文字)
修改后的完整代码
import { useState } from 'react'; import { DropdownButton, Dropdown } from 'react-bootstrap'; import { useTranslation } from 'react-i18next'; import PL from './path-to-pl-flag.png'; // 替换为你的国旗实际路径 import UK from './path-to-uk-flag.png'; const DropdownLanguage = () => { const { i18n } = useTranslation(); const [language, setLanguage] = useState("pl"); // 直接接收选中的value作为参数 const handleLangChange = (selectedLang) => { console.log(selectedLang); setLanguage(selectedLang); i18n.changeLanguage(selectedLang); }; // 动态生成当前选中的标题内容 const getCurrentTitle = () => { const flag = language === 'pl' ? PL : UK; const text = language.toUpperCase(); return ( <> <img className="flag" src={flag} /> {text} </> ); }; return ( <> <DropdownButton id="dropdown-basic-button" title={getCurrentTitle()} // 动态显示当前选中的语言 value={language} onSelect={handleLangChange} > <Dropdown.Item value="pl"> <img className="flag" src={PL} /> PL </Dropdown.Item> <Dropdown.Item value="en"> <img className="flag" src={UK} /> EN </Dropdown.Item> </DropdownButton> </> ); }; export default DropdownLanguage;
关键说明:
- React Bootstrap的
onSelect回调会自动将选中项的value作为第一个参数传入,无需通过事件对象获取 - 动态title的优化可以让用户直观看到当前选中的语言,提升交互体验
- 确保你的国旗图片路径正确,
className="flag"的样式能正常渲染图片(比如设置合适的宽高)
内容的提问来源于stack exchange,提问作者Jakub Marek Stankiewicz
相关产品推荐
相关产品推荐

