美文网首页
React Native TextInput focus时,第一

React Native TextInput focus时,第一

作者: Ager张卫刚 | 来源:发表于2017-08-23 17:24 被阅读114次

问题:TextInput focus时,第一次点击 ScrollView 无效,第二次正常

代码如下(FlatList 继承于ScrollView,以FlatList为例演示):

          <TextInput
              placeholder='test'
              value={this.state.inputText}
              onChangeText={(inputText) => this.setState({inputText})}
              style={{marginBottom: 20, fontSize: 17, width: 300, textAlign: 'center'}}
          />
          <FlatList
              data={[{key: 'item 1'}, {key: 'item 2'}]}
              renderItem={({item}) =>
                  <TouchableHighlight onPress={() =>
                  {
                      console.log('item press');
                  }}
                                      underlayColor='#dddddd'>
                      <View style={{height: 40}}>
                          <Text style={{fontSize: 16, textAlign: 'center'}}>{item.key}</Text>
                      </View>
                  </TouchableHighlight>
             }
          />
image.png

在 TextInput 输入任意字符,第一次点击‘item 1’或者‘item 2’,控制台没有console;第二次才会有。

解决办法

在FlatList 添加keyboardShouldPersistTaps={'handled'}, 并且在 <TouchableHighlight> onPress 方法内 添加 Keyboard.dismiss()

FlatList 如下:

<FlatList
              keyboardShouldPersistTaps={'handled'}
              data={[{key: 'item 1'}, {key: 'item 2'}]}
              renderItem={({item}) =>
                  <TouchableHighlight onPress={() =>
                  {
                      console.log('item press');
                      Keyboard.dismiss();
                  }}
                                      underlayColor='#dddddd'>
                      <View style={{height: 40}}>
                          <Text style={{fontSize: 16, textAlign: 'center'}}>{item.key}</Text>
                      </View>
                  </TouchableHighlight>
             }
          />

结论

解决办法适用于ScrollView,FlatList,SectionList

相关文章

网友评论

      本文标题:React Native TextInput focus时,第一

      本文链接:https://www.haomeiwen.com/subject/yiqjdxtx.html