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

React Native中react-native-autocomplete-input使用问题求助

react-native-autocomplete-input 两个异常问题修复方案

问题根因

  • 键盘输入后自动收起:flatListProps内的keyExtractor写法错误,回调参数顺序搞反,将数字类型的索引idx当做列表项取Water_Source_Code属性,最终所有列表项返回的key都是undefined。每次输入触发状态更新重渲染时,列表Diff逻辑完全失效,整个Autocomplete组件被重复卸载、重建,输入框直接失焦触发键盘收起。
  • RTL从右到左对齐不生效:该组件默认的输入框、下拉结果容器样式没有适配RTL规则,不会自动继承全局RTL配置,需要手动传入样式覆盖默认值。

修复后完整代码

<Autocomplete
  data={
    autoCompleteWaterSourceData?.length === 1 && autoCompleteWaterSourceData[0]
      ? []
      : autoCompleteWaterSourceData
  }
  placeholder={placeholder1}
  value={querySourceCode}
  autoCorrect={false}
  onChangeText={setQuerySourceCode}
  // 输入框容器RTL配置
  inputContainerStyle={{
    direction: 'rtl'
  }}
  // 输入框文本RTL配置
  style={{
    textAlign: 'right',
    writingDirection: 'rtl'
  }}
  // 下拉列表容器RTL配置
  listContainerStyle={{
    direction: 'rtl'
  }}
  flatListProps={{
    keyboardShouldPersistTaps: 'always',
    // 修正keyExtractor:直接取列表项的唯一编码作为key
    keyExtractor: (item) => item.Water_Source_Code,
    style: {
      direction: 'rtl'
    },
    contentContainerStyle: {
      alignItems: 'flex-end'
    },
    renderItem: ({ item: { Water_Source_Code, Water_Source_Name } }) => (
      <TouchableOpacity
        onPress={() =>
          setQuerySourceCode(`${Water_Source_Code} ${Water_Source_Name}`)
        }
      >
        <Text style={[styles.autoCompleteText, { textAlign: 'right' }]}>
          {`${Water_Source_Code} ${Water_Source_Name}`}
        </Text>
      </TouchableOpacity>
    )
  }}
/>

补充说明:如果项目全局适配RTL,可以在应用入口文件配置I18nManager.forceRTL(true),后续组件会默认按RTL规则渲染,无需单独给每个组件加对齐样式。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.27 17:06:27