react-native - 调用时在键盘顶部添加一个按钮
问题描述
我想看看我是否可以在键盘顶部添加一个按钮,当它被调用时我已经在许多应用程序中看到了这个功能,但不确定它是否可能在 expo 和 react-native 上。该按钮应与键盘一起出现,并在按下或键盘消失时变得不可见。我已经放了一个与添加的图像一起使用的示例类
import React, {Component} from 'react';
import {
StyleSheet,
View,
TextInput
} from 'react-native';
export default class test extends Component {
constructor(props) {
super(props);
this.state = {
a: props.navigation,
b: '',
}
}
componentWillMount() {
}
render() {
return (
<View style={styles.container}>
<TextInput
style={{marginTop: 300,marginLeft: 50,borderWidth: 1}}
placeholder="type"
/>
</View>
);
}
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: 22,
backgroundColor: '#42444f',
},
});
解决方案
试试这个方法
constructor(props)
{
super(props)
this.state = {
buttonVisible: false // add this state. this state is the flag for button appearance
}
}
componentDidMount() {
this.keyboardDidShowListener = Keyboard.addListener(
'keyboardDidShow',
this._keyboardDidShow,
);
this.keyboardDidHideListener = Keyboard.addListener(
'keyboardDidHide',
this._keyboardDidHide,
);
}
_keyboardDidShow = () => {
this.setState({
buttonVisible: true
})
}
_keyboardDidHide = () => {
this.setState({
buttonVisible: false
})
}
render() {
return (
<View style={styles.container}>
<View style={{ flex: 4 }}>
<TextInput
style={{marginTop: 300,marginLeft: 50,borderWidth: 1}}
placeholder="type"
/>
</View>
<View style={{ flex: 1 }}>
{this.state.buttonVisible ? <TouchableOpacity style={{ flex: 1, backgroundColor: 'red', justifyContent: 'center', alignItems: 'center' }}><Text>Button</Text></TouchableOpacity> : <View/>}
</View>
</View>
);
}
该按钮将根据buttonVisible
状态值可见,在初始化的键盘事件侦听器内更改状态componentDidMount
推荐阅读
- if-statement - 如果所有非空值都相同,则返回值的公式,否则返回空?
- php - PHP多维数组:删除外部数组,删除索引键和用逗号分隔的剩余数组
- java - 这个回报有什么问题?
- android - Ionic 4 - 安装运行执行完整的构建和安装,因为设备上的安装与磁盘上的本地构建不匹配
- pdflib - PDFlib - 围绕中心旋转任意角度的对象
- mysql - 使用 SELECT 时如何更改属性名称?
- java - 我如何将所有子文件夹添加到类路径 [like -cp "lib\**\*"]
- regex - 有没有办法用正则表达式触发器制作崇高的片段?
- go - 理解 GO 变量赋值
- python - Django 频道无法从异常中导入名称 RequestAborted