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

React中Array.filter()在iPhone端无搜索结果,PC端运行正常

React搜索功能iOS端(Safari/Chrome)异常问题

问题详情

我在React项目中实现了搜索功能,相关代码如下:

过滤函数代码

const searchArray = stats.filter((dish) =>
    dish.dishName.toLowerCase().includes(searchTerm)
);

组件代码

<div className="input-group-sm stock mb-3 m-auto">
  <input
    type="search"
    className="form-control m-auto mb-4 mt-4 searchWindow"
    placeholder="Sök maträtten"
    aria-label="Sök..."
    aria-describedby="button-addon2"
    onChange={(e) => setSearchTerm(e.target.value)}
    value={searchTerm}
  />
</div>
<div>
  <ul className="searchResult">
    <li>{searchArray.map(CreateRecord)}</li>
  </ul>
</div>

CSS样式代码

.searchResult {
    display: flex;
    flex-direction: column;
    height: 350px;
    padding: 0px;
    overflow-y: scroll;
    /* Add the ability to scroll */
    -ms-overflow-style: none;
    /* IE and Edge */
    scrollbar-width: none;
    /* Firefox */
}
.searchResult::-webkit-scrollbar {
    display: none;
}

该功能在PC端运行完全正常,但在iPhone的Safari或Chrome浏览器中,输入搜索文本后所有结果都会消失,请问这是什么原因?


原因分析与修复方案

核心原因

  • 大小写匹配逻辑不一致:仅对dishName做小写转换,未处理searchTerm的大小写,iOS端输入框的自动大写/修正功能会导致搜索词与目标值大小写不匹配。
  • 非英文字符转换兼容性问题:iOS WebKit内核对带有变音符号的字符(如瑞典语的ö)执行toLowerCase()时,可能出现和PC端不一致的转换结果,直接导致匹配失败。
  • type="search"的默认行为干扰:iOS的搜索类型输入框自带自动修正、首字母大写等特性,会改变实际输入的searchTerm值,破坏匹配逻辑。

修复方案

  1. 统一双方大小写转换
    对searchTerm也执行小写转换,确保匹配逻辑两端格式统一:

    const searchArray = stats.filter((dish) =>
        dish.dishName.toLowerCase().includes(searchTerm.toLowerCase())
    );
    
  2. 使用本地化大小写转换(针对非英语场景)
    如果涉及瑞典语等带变音符号的语言,用toLocaleLowerCase指定本地化规则,避免字符转换异常:

    const searchArray = stats.filter((dish) =>
        dish.dishName.toLocaleLowerCase('sv-SE').includes(searchTerm.toLocaleLowerCase('sv-SE'))
    );
    
  3. 禁用输入框自动处理特性(可选)
    将输入框类型改为text,并手动禁用自动大写、自动修正,避免iOS默认行为干扰:

    <input
      type="text"
      className="form-control m-auto mb-4 mt-4 searchWindow"
      placeholder="Sök maträtten"
      aria-label="Sök..."
      aria-describedby="button-addon2"
      onChange={(e) => setSearchTerm(e.target.value)}
      value={searchTerm}
      autoCapitalize="none"
      autoCorrect="off"
    />
    

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.10 22:20:47