如何在单击时关闭键盘并处理可触摸按压 – React Native

huangapple go评论76阅读模式
英文:

How to dismiss keyboard and handle Touchable press in single tap - React Native

问题

我有以下简化的React Native代码:

<ScreenContainer>
  <View>
    <TextInput
      value={query}
      onChangeText={handleInputChange}
      autoFocus={true}
      onSubmitEditing={() => {}}
    />
  </View>

  <SafeAreaView>
    <FlatList
      data={results.length > 0 ? results : null}
      keyExtractor={(item) => item.id}
      renderItem={({ item }) => (
        <View>
          <TouchableOpacity onPress={() => handlePress(item)}>
            // Some other text
          </TouchableOpacity>
        </View>
      )}
    />
  </SafeAreaView>
</ScreenContainer>

TextInput 是一个搜索栏,会动态改变 Flatlist 中的项目。Flatlist 中的每个项目都渲染为 TouchableOpacity。非常简单。

目前,当搜索结果出现并且我点击 TouchableOpacity 时,需要两次点击才能注册 handlePress 事件:第一次点击是为了关闭键盘,第二次才是真正的处理点击事件。

有没有人知道如何在一次点击中处理点击事件并关闭键盘?也许我应该使用不同的组件或以不同的方式构建我的 JSX 结构?

英文:

I have the following simplified React Native code:

<!-- begin snippet: js hide: false console: true babel: false -->

<!-- language: lang-js -->

&lt;ScreenContainer&gt;
  &lt;View&gt;
    &lt;TextInput
      value={query}
      onChangeText={handleInputChange}
      autoFocus={true}
      onSubmitEditing={() =&gt; {}}
    /&gt;
  &lt;/View&gt;

  &lt;SafeAreaView&gt;
    &lt;FlatList
      data={results.length &gt; 0 ? results : null}
      keyExtractor={(item) =&gt; item.id}
      renderItem={({ item }) =&gt; (
        &lt;View&gt;
          &lt;TouchableOpacity onPress={() =&gt; handlePress(item)}&gt;
            // Some other text
          &lt;/TouchableOpacity&gt;
        &lt;/View&gt;
      )}
    /&gt;
  &lt;/SafeAreaView&gt;
&lt;/ScreenContainer&gt;

<!-- end snippet -->

The TextInput is a search bar that dynamically changes the items in the Flatlist. Each item in the Flatlist renders a TouchableOpacity. Simple enough

Currently, when a search result appears and I tap on the TouchableOpacity, it takes 2 presses to register the handlePress event: 1 press to dismiss the keyboard and the next to actually handle the press.

Does anyone know how to handle the press and dismiss the keyboard in 1 press? Maybe I should be using a different component or structure my jsx differently?

答案1

得分: 1

你正在寻找keyboardShouldPersistTaps属性。

英文:

You're looking for the keyboardShouldPersistTaps property.

huangapple
  • 本文由 发表于 2023年6月26日 06:17:54
  • 转载请务必保留本文链接:https://go.coder-hub.com/76552627.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定