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

React中筛选无匹配组件时如何在空div内展示提示消息?

实现方案

你之前使用CSS:empty选择器的方案失效,原因是该选择器无法区分「未触发搜索、容器自然为空」和「搜索后无匹配结果、容器为空」两种场景,且React渲染时JSX的换行、空白符也可能干扰:empty的匹配结果,更可靠的实现方式是通过JSX条件渲染处理,具体改法如下:

  1. 先新增一个搜索状态标记(例如isSearched),初始值为false,用户触发搜索操作(点击搜索按钮/输入搜索关键词触发请求)时将其设为true
  2. 将列表筛选逻辑抽离为单独变量,方便判断长度
  3. 按条件渲染对应内容,修改后的代码示例如下:
// 抽离筛选逻辑
const filteredGames = games.filter(game => game.background_image !== null && game.ratings_count > 38)

<div className="search-res">
  {isSearched ? (
    filteredGames.length ? (
      filteredGames.map(game => (
        <SearchRes
          key={game.name} 
          title={game.name} 
          rating={game.metacritic === null ? <MdGamepad/> : game.metacritic} 
          genre={game.genres.map(genre => genre.name + " ")} 
          imglnk={game.background_image || ""}
          gameid={game.id}
          slug={game.slug}
          plat={game.parent_platforms}
        />
      ))
    ) : <p>No results found</p>
  ) : null}
</div>

如果你的业务场景不需要区分未触发搜索的状态,只需要在筛选后列表为空时展示提示,直接去掉isSearched的判断即可:

const filteredGames = games.filter(game => game.background_image !== null && game.ratings_count > 38)

<div className="search-res">
  {filteredGames.length ? (
    filteredGames.map(game => (
      <SearchRes
        key={game.name} 
        title={game.name} 
        rating={game.metacritic === null ? <MdGamepad/> : game.metacritic} 
        genre={game.genres.map(genre => genre.name + " ")} 
        imglnk={game.background_image || ""}
        gameid={game.id}
        slug={game.slug}
        plat={game.parent_platforms}
      />
    ))
  ) : <p>No results found</p>}
</div>

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.03 01:18:03