Zac*_*ach 8 javascript react-native
假设我有一个绝对位于屏幕底部的视图.该视图包含文本输入.当文本输入被聚焦时,我希望视图的底部触摸键盘的顶部.
我一直在搞乱KeyboardAvoidingView,但键盘一直在我的视线上.是否不可能使这个位置绝对适用?
我可以尝试其他什么方法?谢谢!
vak*_*nzi 11
几天前我遇到了同样的问题(虽然我有一个复杂的TextInput视图作为孩子)并且不仅希望聚焦TextInput而且希望整个视图"附加"到键盘上.最终对我有用的是以下代码:
constructor(props) {
super(props);
this.paddingInput = new Animated.Value(0);
}
componentWillMount() {
this.keyboardWillShowSub = Keyboard.addListener('keyboardWillShow', this.keyboardWillShow);
this.keyboardWillHideSub = Keyboard.addListener('keyboardWillHide', this.keyboardWillHide);
}
componentWillUnmount() {
this.keyboardWillShowSub.remove();
this.keyboardWillHideSub.remove();
}
keyboardWillShow = (event) => {
Animated.timing(this.paddingInput, {
duration: event.duration,
toValue: 60,
}).start();
};
keyboardWillHide = (event) => {
Animated.timing(this.paddingInput, {
duration: event.duration,
toValue: 0,
}).start();
};
render() {
return (
<KeyboardAvoidingView behavior='padding' style={{ flex: 1 }}>
[...]
<Animated.View style={{ marginBottom: this.paddingInput }}>
<TextTranslateInput />
</Animated.View>
</KeyboardAvoidingView>
);
}
Run Code Online (Sandbox Code Playgroud)
你在哪里[...]有其他观点.
自定义挂钩:
import { useRef, useEffect } from 'react';
import { Animated, Keyboard, KeyboardEvent } from 'react-native';
export const useKeyboardHeight = () => {
const keyboardHeight = useRef(new Animated.Value(0)).current;
useEffect(() => {
const keyboardWillShow = (e: KeyboardEvent) => {
Animated.timing(keyboardHeight, {
duration: e.duration,
toValue: e.endCoordinates.height,
useNativeDriver: true,
}).start();
};
const keyboardWillHide = (e: KeyboardEvent) => {
Animated.timing(keyboardHeight, {
duration: e.duration,
toValue: 0,
useNativeDriver: true,
}).start();
};
const keyboardWillShowSub = Keyboard.addListener(
'keyboardWillShow',
keyboardWillShow
);
const keyboardWillHideSub = Keyboard.addListener(
'keyboardWillHide',
keyboardWillHide
);
return () => {
keyboardWillHideSub.remove();
keyboardWillShowSub.remove();
};
}, [keyboardHeight]);
return keyboardHeight;
};
Run Code Online (Sandbox Code Playgroud)
@jazzdle 示例效果很好!谢谢你!只需添加一个 - 在keyboardWillShow方法中,可以添加event.endCoordinates.height因此 paddingBottom 与键盘的高度完全相同。
keyboardWillShow = (event) => {
Animated.timing(this.paddingInput, {
duration: event.duration,
toValue: event.endCoordinates.height,
}).start();
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
3749 次 |
| 最近记录: |