首页 > 解决方案 > 调用时在键盘顶部添加一个按钮

问题描述

我想看看我是否可以在键盘顶部添加一个按钮,当它被调用时我已经在许多应用程序中看到了这个功能,但不确定它是否可能在 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',
},

});

标签: react-nativeexpo

解决方案


试试这个方法

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


推荐阅读