React Native 中输入输入框时如何设置键盘上方的文本输入框

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

我正在使用 react-native TextInput 组件。如果用户点击 textInput 字段,我需要在键盘上方显示 InputBox。

我在下面尝试过,但我遇到了问题

1。键盘避免视图

 a. Here it shows some empty space below the input box 
 b. Manually I need to scroll up the screen to see the input field which I was given in the text field
 c. Input box section is hiding while placing the mouse inside the input box 

2。反应本机键盘感知滚动视图

a.It shows some empty space below the input box
b.ScrollView is reset to the top of the page after I moving to the next input box

这里我在 ScrollView 组件里面设置了 Keyboard-aware-scroll-view

请澄清

我的示例代码是

<SafeAreaView>
<KeyboardAvoidingView>
<ScrollView>        
        <Text>Name</Text>
            <AutoTags
            //required
             suggestions={this.state.suggestedName}
             handleAddition={this.handleAddition}
             handleDelete={this.handleDelete}
             multiline={true}
             placeholder="TYPE IN"
             blurOnSubmit={true}
             style= {styles.style}
             />
</ScrollView>   
</KeyboardAvoidingView>
</SafeAreaView>

[https://github.com/APSL/react-native-keyboard-aware-scroll-view]

react-native textbox keyboard-events textinput
14个回答
13
投票

给你的 TextInput 一个 position: absolute 样式,并使用 keyboardDidShow 和 keyboardDidHide 事件返回的高度改变它的位置。

这里是对 React Native 文档 中键盘示例的修改,用于演示:

import React, { Component } from 'react';
import { Keyboard, TextInput } from 'react-native';

class Example extends Component {
    state = {
        keyboardOffset: 0,
    };

    componentDidMount() {
        this.keyboardDidShowListener = Keyboard.addListener(
            'keyboardDidShow',
            this._keyboardDidShow,
        );
        this.keyboardDidHideListener = Keyboard.addListener(
            'keyboardDidHide',
            this._keyboardDidHide,
        );
    }

    componentWillUnmount() {
        this.keyboardDidShowListener.remove();
        this.keyboardDidHideListener.remove();
    }

    _keyboardDidShow(event) {
        this.setState({
            keyboardOffset: event.endCoordinates.height,
        })
    }

    _keyboardDidHide() {
        this.setState({
            keyboardOffset: 0,
        })
    }

    render() {
        return <View style={{flex: 1}}>
            <TextInput
                style={{
                    position: 'absolute',
                    width:    '100%',
                    bottom:   this.state.keyboardOffset,
                }}
                onSubmitEditing={Keyboard.dismiss}
            />
        </View>;
    }
}

12
投票

首先,Android 平台不需要任何额外的代码。 只需将您的输入保存在

ScrollView
中。只需使用
KeyboardAvoidingView
封装iOS平台的
ScrollView
即可。

创建如下所示的函数,其中包含所有输入

renderInputs = () => {
    return (<ScrollView
        showsVerticalScrollIndicator={false}
        style={{
            flex: 1,
        }}
        contentContainerStyle={{
            flexGrow: 1,
        }}>
        <Text>Enter Email</Text>
        <TextInput
            style={styles.text}
            underlineColorAndroid="transparent"
        />
    </ScrollView>)
}

然后在主视图中渲染它们,如下所示

{Platform.OS === 'android' ? (
    this.renderInputs()
) : (
    <KeyboardAvoidingView behavior="padding">
        {this.renderInputs()}
    </KeyboardAvoidingView>
)}

我用过这个方法,我可以保证它有效。 如果它不起作用,那么您可能会遗漏一些东西。


10
投票

您可以使用滚动视图并将所有组件放入滚动视图中,然后将

automaticallyAdjustKeyboardInsets
属性添加到滚动视图。它将解决您的问题。

automaticallyAdjustKeyboardInsets
控制 ScrollView 是否应该自动调整其 contentInset 和 当键盘改变其大小时 scrollViewInsets。默认值为 false。

<ScrollView automaticallyAdjustKeyboardInsets={true}>

          {allChildComponentsHere}
         <View style={{ height: 30 }} />//added some extra space to last element
</ScrollView>

希望有帮助。


9
投票

挂钩版本:

const [keyboardOffset, setKeyboardOffset] = useState(0);
const onKeyboardShow = event => setKeyboardOffset(event.endCoordinates.height);
const onKeyboardHide = () => setKeyboardOffset(0);
const keyboardDidShowListener = useRef();
const keyboardDidHideListener = useRef();

useEffect(() => {
  keyboardDidShowListener.current = Keyboard.addListener('keyboardWillShow', onKeyboardShow);
  keyboardDidHideListener.current = Keyboard.addListener('keyboardWillHide', onKeyboardHide);

  return () => {
    keyboardDidShowListener.current.remove();
    keyboardDidHideListener.current.remove();
  };
}, []);

6
投票

你可以使用KeyboardAvoidingView如下

if (Platform.OS === 'ios') {
        return <KeyboardAvoidingView behavior="padding">
            {this.renderChatInputSection()}
        </KeyboardAvoidingView>
    } else {
        return this.renderChatInputSection()
    }

this.renderChatInputSection()
将返回视图,如用于输入消息的 textinput。希望这会对你有所帮助。


1
投票

对于Android,您可以在

android:windowSoftInputMode="adjustResize"
文件中为
Activity
设置
AndroidManifest
,因此当键盘显示时,您的屏幕将调整大小,如果您将
TextInput
放在屏幕底部,它将保持在键盘上方


1
投票

在你的 android/app/src/main/AndroidManifest.xml 中写下这两行 内部活动标签

android:launchMode="singleTask" android:windowSoftInputMode="stateAlwaysHidden|adjustPan"


0
投票

react-native-keyboard-aware-scroll-view 在 ios 中引起了类似的问题。那时我遇到了react-native-keyboard-aware-view。片段几乎相同。

    <KeyboardAwareView animated={true}>
        <View style={{flex: 1}}>
          <ScrollView style={{flex: 1}}>
              <Text style={{fontSize: 20, color: '#FFFFFF'}}>A</Text>
              <Text style={{fontSize: 20, color: '#FFFFFF'}}>B</Text>
              <Text style={{fontSize: 20, color: '#FFFFFF'}}>C</Text>
              <Text style={{fontSize: 20, color: '#FFFFFF'}}>D</Text>
          </ScrollView>
        </View>
        <TouchableOpacity style={{height: 50, backgroundColor: 'transparent', alignItems: 'center', justifyContent: 'center', alignSelf: 'stretch'}}>
          <Text style={{fontSize: 20, color: '#FFFFFF'}}>Submit</Text>
        </TouchableOpacity>
      </KeyboardAwareView>

希望有帮助


0
投票

你一定会发现这个有用

键盘感知滚动视图 Android 问题

真不知道为什么要加

“androidStatusBar”:{ “背景颜色”:“#000000” }

让 KeyboardawareScrollview 工作

注意:不要忘记在没有最后一步的情况下重新启动项目它可能无法工作 享受!


0
投票

我在做我的副项目时遇到了同样的问题,我在稍微调整 KeyboardAvoidingView 后解决了它。 我将我的解决方案发布到npm,请尝试一下并给我反馈! Demo on iOS

示例片段

import React from 'react';
import { StyleSheet, TextInput } from 'react-native';
import KeyboardStickyView from 'rn-keyboard-sticky-view';

const KeyboardInput = (props) => {
  const [value, setValue] = React.useState('');

  return (
    <KeyboardStickyView style={styles.keyboardView}>
      <TextInput
        value={value}
        onChangeText={setValue}
        onSubmitEditing={() => alert(value)}
        placeholder="Write something..."
        style={styles.input}
      />
    </KeyboardStickyView>
  );
}

const styles = StyleSheet.create({
  keyboardView: { ... },
  input: { ... }
});

export default KeyboardInput;


0
投票

我的解决方案基于@basbase 解决方案。

我的问题是他的解决方案使 TextInput 跳起来而不考虑我的整体观点。

这不是我想要的,所以我按照他的建议做了,但做了一点修改

只需给父视图这样的样式:

 <View 
             style={{
              flex: 1,
              bottom:   keyboardOffset,
          }}>

它会起作用的!唯一的问题是,如果键盘打开并且您向下滚动,您会在屏幕末尾看到额外的空白填充。


0
投票

flexGrow: 1
是关键。

像下面这样使用它:

<ScrollView contentContainerStyle={styles.container}>
  <TextInput
    label="Note"
    value={currentContact.note}
    onChangeText={(text) => setAttribute("note", text)}
  />
</ScrollView>
const styles = StyleSheet.create({
  container: {
    flexGrow: 1,
  },
});

-1
投票

最好最简单的方法是使用 Scroll View ,它会自动将内容向上移动并且 TextInput 不会被隐藏,可以参考下面的代码

  <ScrollView style={styles.container}>
  <View>
    <View style={styles.commonView}>
      <Image source={firstNameIcon} style={{width: 25, height: 25}}></Image>
      <Text style={styles.commonTxt}>First Name</Text>
    </View>

    <TextInput
      onFocus={() => onFocus('firstName')}
      placeholder="First Name"
      style={styles.txtInput}
      onChangeText={(text) => onChangeText(text, 'firstName')}
      value={firstNameValue}
    />
  </View>
  <View>
    <View style={styles.commonView}>
      <Image source={LastNameIcon} style={{width: 25, height: 25}}></Image>
      <Text style={styles.commonTxt}>Last Name</Text>
    </View>

    <TextInput
      onFocus={() => onFocus('lastName')}
      placeholder="Last Name"
      style={styles.txtInput}
      onChangeText={(text) => onChangeText(text, 'lastName')}
      value={lastNameValue}
    />
  </View>
  <View>
    <View style={styles.commonView}>
      <Image source={callIcon} style={{width: 25, height: 25}}></Image>
      <Text style={styles.commonTxt}>Number</Text>
    </View>

    <TextInput
      onFocus={() => onFocus('number')}
      placeholder="Number"
      style={styles.txtInput}
      onChangeText={(text) => onChangeText(text, 'number')}
      value={numberValue}
    />
  </View>
  <View>
    <View style={styles.commonView}>
      <Image source={emailIcon} style={{width: 25, height: 25}}></Image>
      <Text style={styles.commonTxt}>Email</Text>
    </View>

    <TextInput
      onFocus={() => onFocus('email')}
      placeholder="Email"
      style={styles.txtInput}
      onChangeText={(text) => onChangeText(text, 'email')}
      value={emailValue}
    />
  </View>

  <View style={styles.viewSavebtn}>
    <TouchableOpacity style={styles.btn}>
      <Text style={styles.saveTxt}>Save</Text>
    </TouchableOpacity>
  </View>
</ScrollView>

-1
投票

转到你的 Android>app>src>main>AndroidManifest.xml 写下这两行:

android:launchMode="singleTop" android:windowSoftInputMode="adjustPan"

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