Подтвердить что ты не робот

React-native, как перемещать экран вверх по textinput

У меня есть экран входа в систему, созданный с использованием реакции-native.

Как я могу сменить свой экран, когда пользователь вводит текст в текстовом поле?

Я слушаю событие onFocus() и использую стиль CSS, чтобы изменить стиль представления?

4b9b3361

Ответ 1

Вы можете использовать ScrollView для управления движениями вверх и вниз. Пока пользователь не сфокусировал TextInput, вы можете отключить прокрутку. В режиме фокуса просто сдвиньте scrollview с помощью Сопоставление содержимого.

<TextInput
    onFocus={this.textInputFocused.bind(this)}
  />

textInputFocused() {
//do your stuff here. scroll screen up
}

Надеюсь, что это поможет!

Ответ 2

В 2017 году (RN 0,43) для этого есть специальный компонент: KeyboardAvoidingView

Ответ 3

Ответ на ночную ярость довольно хорош, но не будет суетиться с ScrollView contentOffset, я бы использовал ScrollResponder:

render() {
  return (
    <ScrollView ref="myScrollView">
      <TextInput
        ref="myInput"
        onFocus={this._scrollToInput.bind(this)}
      />
    </ScrollView>
  );
}

_scrollToInput {
  const scrollResponder = this.refs.myScrollView.getScrollResponder();
  const inputHandle = React.findNodeHandle(this.refs.myInput)

  scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
    inputHandle, // The TextInput node handle
    0, // The scroll view bottom "contentInset" (default 0)
    true // Prevent negative scrolling
  );
}

См. определение метода: scrollResponderScrollNativeHandleToKeyboard

Ответ 4

Этот пакет выполняет greate-задание, вводит компонент KeyboardAwareScrollView, который прокручивает представление до ввода ввода с клавиатуры, а затем прокручивается вниз.

Ответ 5

И другое решение, работающее с RN 0.2, на этот раз вместо того, чтобы раздавить содержимое, которое он прокручивает.

 inputFocused: function(ref) {
   this._scroll(ref, 75);
 },

 inputBlurred: function(ref) {
   this._scroll(ref, 0);
 },

 _scroll: function(ref, offset) {
   setTimeout(() => {
     var scrollResponder = this.refs.myScrollView.getScrollResponder();
     scrollResponder.scrollResponderScrollNativeHandleToKeyboard(
                React.findNodeHandle(this.refs[ref]),
                offset,
                true
            );
     });
  },

...

render: function() {
  return <View style={{flex: 1}}> 
    <ScrollView ref="myScrollView" keyboardDismissMode='interactive' contentContainerStyle={{flex: 1}}>
      <TextInput
        ref="myInput"
        onFocus={this.inputFocused.bind(this, 'myInput')}
        onBlur={this.inputBlurred.bind(this, 'myInput')} />
    </ScrollView>
  </View>
}

Ответ 6

Это дерьмовая стрельба, чтобы получить функциональность встроенной клавиатуры ScrollView. Для моего Android-приложения он отлично работает на одном экране, который почти идентичен другому, для которого не работает. И на iOS это просто не работает. Это то, что работает для меня:

import { Keyboard, ScrollView, StyleSheet, View } from 'react-native';

this.state = {
    filler: false,
}

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

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

_keyboardDidShow() {
    this.setState({filler: true})
    setTimeout(() => this.vertical && this.vertical.scrollToEnd({animated: true}), 0);
}

_keyboardDidHide() {
    this.setState({filler: false})
}


...
return (
  <ScrollView ref={ref => this.vertical = ref}>
    <TextInput/>
    { this.state.filler ? <View style={styles.filler}/> : null }
  </ScrollView>
)

styles.filler = {
    height: 'Keyboard Height'
}

Примечание. Это может работать только в том случае, если ваш <TextInput/> находится в нижней части экрана, который был в моем случае.

Ответ 7

Попробуйте установить multiline={true} prop для TextInput. Это сработало для меня.

Ответ 8

import {KeyboardAvoidingView} from 'react-native';

<KeyboardAvoidingView style={styles.container} behavior="padding" enabled>

    <Text style={{height: 100, marginTop: 30}}> test text before input</Text>
    <Text style={{height: 100, marginTop: 30}}> test text before input</Text>
    <Text style={{height: 100, marginTop: 30}}> test text before input</Text>
    <Text style={{height: 100, marginTop: 30}}> test text before input</Text>
    <Text style={{height: 100, marginTop: 30}}> test text before input</Text>

    <TextInput
        style={{height: 40, borderColor: 'gray', borderWidth: 1}}
        onChangeText={(text) => this.setState({text})}
        value={this.state.text}
    />

    <Text style={{height: 100, marginTop: 20}}>1 test text after input</Text>
    <Text style={{height: 100, marginTop: 20}}>2 test text after input</Text>
    <Text style={{height: 100, marginTop: 20}}>3 test text after input</Text>
    <Text style={{height: 100, marginTop: 20}}>4 test text after input</Text>
    <Text style={{height: 100, marginTop: 20}}>5 test text after input</Text>

</KeyboardAvoidingView>

Запустите перекусить: https://snack.expo.io/H1BE5ZoXV