React-native如何在textinput上移动屏幕

Ste*_* Ng 17 javascript reactjs react-native

我有一个使用react-native创建的登录屏幕.

当用户输入textInput时,如何将屏幕移开?

我是否会听取onFocus()事件并使用css样式来更改视图的样式?

Ale*_*rov 14

在2017年(RN 0.43),有一个特殊的组件:KeyboardAvoidingView

  • @farmcommand2 它有效,但有一些技巧。GitHub 上有 [issue](https://github.com/facebook/react-native/issues/11681#issuecomment-339446150) 提供解决方案。我使用这个:`behavior={(Platform.OS === 'ios') ? '填充':空}` (4认同)
  • 不幸的是,KeyboardAvoidingView 纯粹是垃圾,并不能真正起作用。 (4认同)

Nig*_*ury 6

您可以使用ScrollView控制屏幕的上下移动.只要用户没有聚焦TextInput,您就可以禁用滚动.在焦点上,只需使用Content Offset prop 向上移动滚动视图.

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

textInputFocused() {
//do your stuff here. scroll screen up
}
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你!


Phi*_*sen 5

Night Fury的回答非常好,虽然不会对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's bottom "contentInset" (default 0)
    true // Prevent negative scrolling
  );
}
Run Code Online (Sandbox Code Playgroud)

请参阅方法定义:scrollResponderScrollNativeHandleToKeyboard


Mah*_*our 5

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>
Run Code Online (Sandbox Code Playgroud)

跑在小吃:https : //snack.expo.io/H1BE5ZoXV