在React Native中输入字段时如何在键盘上方设置textinput框

时间:2019-02-06 06:27:33

标签: react-native textbox keyboard-events textinput

我正在使用本机TextInput组件。如果用户单击textInput字段,则需要在键盘上方显示InputBox。

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

1。键盘避开视图

-

2。 react-native-Keyboard-aware-scroll-view

new Date('2019-01-25')
// => Fri Jan 25 2019 05:30:00 GMT+0530 (India Standard Time)
new Date('2019 01 25')
// => Fri Jan 25 2019 00:00:00 GMT+0530 (India Standard Time)

在这里,我在ScrollView组件中设置了键盘感知滚动视图

请澄清

我的示例代码是

 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 

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

11 个答案:

答案 0 :(得分:4)

给TextInput一个位置:绝对样式,并使用keyboardDidShow和keyboardDidHide事件返回的高度更改其位置。

这里是对React Native documentation的Keyboard示例的修改,以进行演示:

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>;
    }
}

答案 1 :(得分:1)

您可以按以下方式使用KeyboardAvoidingView

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

this.renderChatInputSection()将在其中返回类似于textinput的视图以键入消息。希望对您有帮助。

答案 2 :(得分:0)

对于android,您可以在<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:id="@+id/parent" android:layout_width="match_parent" android:layout_height="match_parent" android:background="#FFFFFF"> <android.support.constraint.Guideline android:id="@+id/guideline_ver" android:layout_width="match_parent" android:layout_height="wrap_content" android:orientation="vertical" app:layout_constraintGuide_percent=".5" /> <android.support.constraint.Guideline android:id="@+id/guideline_hor" android:layout_width="wrap_content" android:layout_height="wrap_content" android:orientation="horizontal" app:layout_constraintGuide_percent=".5" /> <View android:id="@+id/topLeft" android:layout_width="0dp" android:layout_height="0dp" android:layout_margin="4dp" android:background="#E02222" app:layout_constraintBottom_toTopOf="@+id/guideline_hor" app:layout_constraintDimensionRatio="h,1:1" app:layout_constraintHeight_default="percent" app:layout_constraintHeight_percent=".5" app:layout_constraintRight_toLeftOf="@+id/guideline_ver" /> <View android:id="@+id/topRight" android:layout_width="0dp" android:layout_height="0dp" android:layout_margin="4dp" android:background="#411010" app:layout_constraintBottom_toTopOf="@+id/guideline_hor" app:layout_constraintDimensionRatio="h,1:1" app:layout_constraintHeight_default="percent" app:layout_constraintHeight_percent=".5" app:layout_constraintLeft_toRightOf="@+id/guideline_ver" /> <View android:id="@+id/bottomLeft" android:layout_width="0dp" android:layout_height="0dp" android:layout_margin="4dp" android:background="#165B92" app:layout_constraintDimensionRatio="h,1:1" app:layout_constraintHeight_default="percent" app:layout_constraintHeight_percent=".5" app:layout_constraintRight_toLeftOf="@+id/guideline_ver" app:layout_constraintTop_toBottomOf="@+id/guideline_hor" /> <View android:id="@+id/bottomRight" android:layout_width="0dp" android:layout_height="0dp" android:layout_margin="4dp" android:background="#680C5F" app:layout_constraintDimensionRatio="h,1:1" app:layout_constraintHeight_default="percent" app:layout_constraintHeight_percent=".5" app:layout_constraintLeft_toRightOf="@+id/guideline_ver" app:layout_constraintTop_toBottomOf="@+id/guideline_hor" /> </android.support.constraint.ConstraintLayout> 文件中为android:windowSoftInputMode="adjustResize"设置Activity,因此,在显示键盘时,屏幕将调整大小,如果将AndroidManifest放在底部屏幕上方,它将保持在键盘上方

答案 3 :(得分: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>

希望它能帮助您

答案 4 :(得分:0)

您肯定会从中找到有用的

Keyboard aware scroll view Android issue

我真的不知道为什么要添加

  

“ androidStatusBar”:{         “ backgroundColor”:“#000000”       }

要使KeyboardawareScrollview正常工作

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

答案 5 :(得分:0)

在处理我的辅助项目时,我遇到了同样的问题,在对KeyboardAvoidingView进行了一些调整之后,我解决了该问题。 我已将my solution发布到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;

答案 6 :(得分:0)

挂钩版本:

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();
  };
}, []);

答案 7 :(得分:0)

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

我的解决方案问题是,它使TextInput跳起来而没有考虑我的整体视图。

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

只需给父级View样式如下:

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

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

答案 8 :(得分:0)

最好的简便方法是使用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>

答案 9 :(得分:0)

我知道这听起来可能是一个愚蠢的主意,但我的键盘问题已通过ScrollView轻松解决。Without keyboard popup view

On keyboard popup view

<View style={{flex:1, height:"100%"}}>
        <ScrollView showsVerticalScrollIndicator={false}>
          <Text>Username</Text>
        <TextInput
          style={styles.TextInput}
          underlineColorAndroid="transparent"
          autoCapitalize="none"
          type="email"
          value={userName}
          onChangeText={(userName) => this.setState({ userName })}
        />
        <Text style={styles.textInputHeader}>Password</Text>
        <TextInput
          style={styles.TextInput}
          secureTextEntry={true}
          underlineColorAndroid="transparent"
          autoCapitalize="none"
          value={password}
          onChangeText={(password) => this.setState({ password })}
        />
        <TouchableOpacity>
          <Text>
            Forgot Password?
          </Text>
        </TouchableOpacity>
        <TouchableOpacity onPress={this.checkInput}>
          <Text>LOGIN</Text>
        </TouchableOpacity>
        <Text onPress={() => this.props.navigation.navigate("SignupScreen")}>Don't have an account? Sign up</Text>
        </ScrollView>
      </View>  
  </View>

答案 10 :(得分:0)

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

android:launchMode="singleTop" android:windowSoftInputMode="adjustPan" enter image description here