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

Typeahead自定义菜单:无结果时显示空值且保留额外菜单项

解决Typeahead自定义菜单后无结果不显示空提示的问题

问题核心是自定义菜单后,底部的额外项让菜单始终有内容,导致Typeahead默认的空结果提示不触发。解决办法很直接:手动判断查询结果是否为空,主动插入空提示项,同时保留底部的分隔线和按钮。

修改后的代码如下:

renderMenu = (results, menuProps) => {
  const { menuFooterButtonOptions } = this.props;
  const items = [];

  // 无查询结果时,添加空提示项
  if (results.length === 0) {
    items.push(
      <MenuItem disabled option={{ key: "empty" }}>
        {/* 复用Typeahead自带的emptyLabel,或者自定义文本 */}
        {menuProps.emptyLabel || "无匹配结果"}
      </MenuItem>
    );
  } else {
    // 有结果时,添加查询结果项
    items.push(...results.map((result, index) => (
      <MenuItem key={index} option={result} position={index}>
        {menuProps.renderMenuItemChildren ? menuProps.renderMenuItemChildren(result, this.props, index) : result}
      </MenuItem>
    )));
  }

  // 添加底部分隔线和按钮(原逻辑保留)
  if (menuFooterButtonOptions && menuFooterButtonOptions?.show) {
    const button = (
      <MenuItem option={{key: "footerButton"}} onClick={(_) => {menuFooterButtonOptions.onClick();}} active={false}>
        <span className="btn-link">
          {menuFooterButtonOptions.text}
        </span>
      </MenuItem>
    );
    items.push(<Menu.Divider />);
    items.push(button);
  }

  return (
    <Menu {...menuProps}>
      {items}
    </Menu>
  );
};

关键细节说明:

  • 给空提示项加上disabled属性,避免用户误选中这个提示项
  • 优先使用menuProps.emptyLabel,和Typeahead默认的空提示文本保持一致,不用额外自定义
  • 空提示项和底部额外项的顺序是:空提示 → 分隔线 → 按钮,逻辑清晰不混乱

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.10 19:44:59