react-native - 单击搜索图标(而不是文本输入)时如何自动打开键盘?
问题描述
我在动画中创建了一个搜索栏,就像单击搜索图标打开时一样,单击关闭时它关闭,但我想做的是当我单击打开搜索栏时,键盘应该打开并专注于 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>
);
}
解决方案
推荐阅读
- javascript - JavaScript 中一年中的哪一天不更新?
- python-3.x - 适用于 python3 google app-engine 的 dev_appserver.py 的 windows 版本的可用性
- windows - 使用直接 URL 重定向 Tomcat 9 和 IIS
- bash - 通过映射到标准输入的套接字与 Systemd 服务通信
- excel - 循环遍历列并将结果保存到新列中
- c - 在C中读取隔行扫描PNG的字节
- python - 将太多参数传递给 Python 中的函数
- angular - 动态值的角度灯箱问题
- reactjs - 在 React Component 状态下实现 Mobx ViewModel
- android - 如何暂停片段?