Ste*_* Ng 17 javascript reactjs react-native
我有一个使用react-native创建的登录屏幕.
当用户输入textInput时,如何将屏幕移开?
我是否会听取onFocus()事件并使用css样式来更改视图的样式?
Ale*_*rov 14
在2017年(RN 0.43),有一个特殊的组件:KeyboardAvoidingView
您可以使用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)
希望能帮助到你!
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
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
| 归档时间: |
|
| 查看次数: |
27459 次 |
| 最近记录: |