首页 > 解决方案 > 单击搜索图标(而不是文本输入)时如何自动打开键盘?

问题描述

我在动画中创建了一个搜索栏,就像单击搜索图标打开时一样,单击关闭时它关闭,但我想做的是当我单击打开搜索栏时,键盘应该打开并专注于 textinput 并清除 textinput 中的文本。

当我在键盘上单击返回时,它应该会自动关闭搜索栏。

下面是我的代码。

import React from 'react';
import { View, TouchableOpacity, SafeAreaView, TextInput, StyleSheet, Animated, Dimensions, TouchableWithoutFeedback, Image, Keyboard} from 'react-native';
import Icon from 'react-native-vector-icons/MaterialIcons';
import { useKeyboard } from '@react-native-community/hooks';
import styled from 'styled-components/native';

const Container = styled(Animated.View)`
  width:50px;
  height:50px;
  background-color: white;
`;
const Input = styled(TextInput)`
  flex:1;
  margin-right: 50px;
  margin-left: 20px;
  color: gray;
`;
const BoxButtonSearch = styled.TouchableOpacity`
  width: 50px;
  height: 50px;
  background-color: white;
  position: absolute;
  left: 0px;
  border-radius: 30px;
  justify-content: center;
  align-items: center;
  align-self: center;
  align-content: center
`;
const BoxButtonClose = styled.TouchableOpacity`
  width: 50px;
  height: 50px;
  background-color: white;
  position: absolute;
  right : 0px;
  border-radius: 30px;
  justify-content: center;
  align-items: center;
`;
const SearchIcon = styled(Icon).attrs({
  name: 'search',
})`
  color: #293894;
  font-size: 30px;
`;
const CloseIcon = styled(Icon).attrs({
  name: 'close',
})`
  color: #293894;
  font-size: 30px;
`;

export default function SearchBar() {
  const animation = new Animated.Value(50);
  const { width } = Dimensions.get('window');
  const keyboard = useKeyboard();

  function onSearch() {
    Animated.spring(animation, {
      toValue: width * 1,
      useNativeDriver: false,
    }).start();
  }
  function onSearchClose() {
    Animated.spring(animation, {
      toValue: width * 0.11,
      useNativeDriver: false,
    }).start();
    Keyboard.dismiss();
  }
  return (
    <SafeAreaView
      style={{ flex: 1, alignItems: 'flex-end', justifyContent: 'center' }}>
      <View style={{ flexDirection: 'row', justifyContent: 'flex-end' }}>
        <View style={{ marginRight: 0, justifyContent: 'center' }}>
          <TouchableWithoutFeedback>
            <Image source={require('./assets/snack-icon.png')} style={{ width: 30, height: 30 }} />
          </TouchableWithoutFeedback>
        </View>
        <View style={{ marginRight: 0 }}>
          <Container style={{ width: animation }}>
            <Input placeholder={'search'} style={{ marginLeft: 50, fontSize: 18 }} />
            <BoxButtonClose onPress={onSearchClose}>
              <CloseIcon />
            </BoxButtonClose>
            <BoxButtonSearch onPress={onSearch}>
              <SearchIcon />
            </BoxButtonSearch>
          </Container>
        </View>
      </View>
    </SafeAreaView>
  );
}

标签: react-nativetextinputsearchbar

解决方案


推荐阅读