我希望所有 subview 都能以一种干净的 Action 移动,但是如果您查看 gif,您会发现 Text subview 和 TextInput subview 重叠并以不同的速度移动。看起来文本 subview 会立即调整其位置,而按钮和 TextInput subview 则以更多的“缓入缓出”方式调整其位置。
主要导出组件
class SearchScreen extends React.Component {
state = {search:""}
render(){
getArguments = {
search: this.state.search
}
return (
<KeyboardAvoidingView behavior="padding" style={styles.container}>
<Text style={styles.searchTitle}>Search for a Movie in the OMDB Database</Text>
<TextInput style={styles.searchField} onChangeText={text => this.setState({search:text})} ></TextInput>
<SearchButton navigation = {this.props.navigation} getArguments={getArguments}/>
</KeyboardAvoidingView>
)
}
}
样式
const styles = StyleSheet.create({
container: {
flex:1,
backgroundColor: '#C8FEFE',
alignItems: 'center',
justifyContent: 'center'
},
searchButton: {
marginTop: 20,
backgroundColor: '#24D9E8',
borderRadius: 5,
padding: 5
},
searchField: {
backgroundColor: '#FFF',
textAlign: 'center',
width: 200,
borderRadius: 5,
margin: 20,
height: 30
},
searchTitle:{
fontWeight: 'bold',
fontSize: 20,
textAlign:'center'
}
});
<小时/>
Github
最佳答案
解决方案 1:针对 iOS 的快速修复
您可以将元素包装在 View 中,这将使它们按照您想要的方式对键盘使用react:
// styles
contentContainer: {
alignItems: 'center',
}
// SearchScreen
<View style={styles.contentContainer}>
<Text style={styles.searchTitle}>Search for a Movie in the OMDB Database</Text>
<TextInput style={styles.searchField} onChangeText={text => this.setState({search:text})} ></TextInput>
<SearchButton navigation = {this.props.navigation} getArguments={getArguments}/>
</View>
但是,这仅适用于 iOS。 Android 上的键盘工作方式略有不同。所以解决方案 2 是一种更可靠的做事方式。
解决方案 2:动画
键盘回避非常棘手,Spencer Carli's article Dominik 提到的是使用 KeyboardAvoidingView
解决方案的重要资源。这些通常会给你你需要的东西。但如果您希望键盘状态之间实现平滑、受控的过渡,则应该使用动画。流程如下:
- 添加Keyboard event listeners到您的组件(
keyboardDidShow
和keyboardDidHide
) - 将要移动的内容封装在
Animated.View
中 - 在
keyboardDidShow
上,按所需的偏移量对Animated.View
的 y 位置进行动画处理。返回的事件(KeyboardEvent
类型)以及Dimensions
API 具有您需要的所有测量值。提示:使用带有贝塞尔曲线的Animated.timing
动画Easing
控制 View 如何移动。 - 在
keyboardDidHide
上,重复动画,但方向相反。
希望这有帮助!
关于javascript - react native : Subviews of KeyboardAvoidingView have lag/move at different speeds,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59514916/