You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

React Bootstrap DropdownButton取值报错:Uncaught TypeError: evt is null

解决DropdownButton无法获取值及evt为null的问题

问题出在React Bootstrap的DropdownButton的onSelect回调参数机制上:它的第一个参数不是事件对象,而是选中的Dropdown.Item的value属性值,你之前沿用了Select组件的事件处理逻辑,所以会出现evt is null的错误。

修改步骤:

  1. 调整handleLangChange函数的参数,直接接收选中的语言值,而非事件对象
  2. 移除evt.target.value的写法,直接使用传入的参数
  3. 可选优化:将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

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.01 14:40:29