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

React项目中react-bootstrap的Dropdown下拉菜单点击后无选项显示问题

React-Bootstrap下拉菜单点击后空白无选项问题解决

问题现象

React项目集成react-bootstrap实现下拉菜单,代码运行无控制台报错,但点击下拉按钮后菜单为空,预设的选项没有渲染。

问题代码

import React, { useState } from 'react';
import 'bootstrap/dist/css/bootstrap.min.css';
import { DropdownButton, Dropdown } from "react-bootstrap";
import "bootstrap/dist/js/bootstrap.min.js";

const App = () => {
  const [cities, setCities] = useState(["agra", "delhi"])
  return (
    <div className="App">
      <h2 className="text-center">Welcome to Nivaran</h2>
      <DropdownButton id="dropdown-basic-button" title="Choose State">
        {cities.map(city => {
          <Dropdown.Item href="#">{city}</Dropdown.Item>
        })}
      </DropdownButton>
    </div>
  );
}

export default App;

问题原因

使用map方法遍历渲染下拉选项时,箭头函数使用了大括号包裹逻辑,但遗漏了return语句,没有返回需要渲染的Dropdown.Item组件,导致最终没有内容输出。

解决方案

修正写法1:显式添加return语句

{cities.map((city) => {
  return <Dropdown.Item href="#">{city}</Dropdown.Item>;
})}

修正写法2:使用箭头函数隐式返回(更简洁)

去掉大括号即可省略return语句,直接返回组件:

{cities.map(city => <Dropdown.Item href="#">{city}</Dropdown.Item>)}

补充建议:遍历渲染列表元素时建议给每个子元素添加唯一的key属性,避免React的diff算法警告,比如写为<Dropdown.Item key={city} href="#">{city}</Dropdown.Item>

内容的提问来源于stack exchange,提问作者yogesh kumar

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 07:45:02