单击即可清除文本

问题描述 投票:0回答:2

[当我第一次单击十字图标时,它会放下键盘,而在第二次点击时,它会清除搜索栏中的文本。我也想尝试其他解决方案,但是第一次却没有任何效果,因此我想在第一次点击时清除文本。我如何清除第一次点击时的文字?

    return (
      <View style={styles.FlatList_header}>
        <View style={styles.header_style}>
          <Input
            autoFocus={true}
            style={styles.textInputStyle}
            onChangeText={text => this.search(text)}
            value={this.state.text}
          />
          <Icon
            name="close"
            style={styles.crossIcon}
            onPress={() => {
              this.search('');
            }}
          />
        </View>
      </View>
    );
  };

  render() {
    const {data, onPress} = this.props;
    return (
      <>
        <SafeAreaView
          style={{flex: 1, backgroundColor: customColor.defaultGreen}}>
          <View style={styles.MainContainer}>
            <FlatList
              data={data}
              renderItem={({item}) => (
                <View
                  style={{
                    flex: 1,
                    borderWidth: 0.5,
                    borderColor: customColor.textLightGrey,
                  }}>
                  <Text
                    style={styles.FlatList_Item}
                    onPress={() => onPress(item)}>
                    {item?.taskName}
                  </Text>
                </View>
              )}
              enableEmptySections={true}
              ListHeaderComponent={this.Render_FlatList_Sticky_header}
              keyExtractor={item => item.id}
            />
          </View>
        </SafeAreaView>
      </>
    );
  }
}
android react-native android-studio searchbar
2个回答
0
投票

在您的onPress函数中执行此操作。

     onPress={() => {
     Keyboard.dismiss()
              this.search('');
     this.setState(text: '')
           }}

此外,在onChangeText时您未设置状态,请在onChangeText中执行此操作>

onChangeText={(text)=>this.setState({text})}

编辑:将此添加到FlatList中>

 keyboardShouldPersistTaps='always'

为ex创建新的状态:按下

。如果用户第一次触摸,请设置为true。并在视图中插入if条件。
<TouchableOpacity onPress={() => this.setState({ pressed: !this.state.pressed})}>
{this.state.pressed ? (
    <Icon
    name="close"
    style={styles.crossIcon}
    onPress={() => {
        this.search('');
    }}
/>
) : (
    <Text>Clear</Text>
)}
</TouchableOpacity>

0
投票

为ex创建新的状态:按下

© www.soinside.com 2019 - 2024. All rights reserved.