Android React Native webview中键盘会遮挡内容

4
我正在使用React Native的<WebView>组件。 文档中没有提到如何处理Android上当<input>元素获得焦点时,键盘会遮挡webview的问题。
有人解决过这个问题吗? 我找到了一个似乎适用于常规<View>的库,但不适用于<WebView>
4个回答

10

你可以使用KeyboardAvoidingView来包裹你的WebView

  <KeyboardAvoidingView
    behavior={Platform.select({ ios: "position", android: null })}
    enabled
    contentContainerStyle={{ flex: 1 }}
    keyboardVerticalOffset={Platform.select({ ios: offset, android: 20 })}
    style={{ flexGrow: 1 }}
  >
    <WebView/>
  </KeyboardAvoidingView>

1
我可以知道 offset 的值是多少吗?在我的 iPhone6 上,当输入框聚焦时,我不得不将它设置为 -50 才能使第一个输入框出现在视图的开头... - Dimitri Kopriwa

3

您是否考虑过响应键盘出现和消失的系统级事件,然后适当地调整WebView大小?

有一个旧问题是如何处理这个问题,可能仍然相关。特别是这个答案展示了如何处理键盘事件:https://dev59.com/jV0b5IYBdhLWcg3wVv-9#33585501

DeviceEventEmitter.addListener('keyboardDidShow',(frames)=>{
  if (!frames.endCoordinates) return;
  this.setState({keyboardSpace: frames.endCoordinates.height});
});
DeviceEventEmitter.addListener('keyboardWillHide',(frames)=>{
  this.setState({keyboardSpace:0});
});

您可以使用frames.endCoordinates.height值来调整WebView的高度,确保内容不会被键盘遮挡。

0

提醒大家,如果您不需要复杂的键盘控制,也可以使用react-native-keyboard-spacer轻松实现此功能。

import KeyboardSpacer from 'react-native-keyboard-spacer';

class DemoApp extends Component {
  render() {
    return (
      <View>
        <WebView ... />
        <KeyboardSpacer/>
      </View>
    );
  }
}

尽管自述文件说它只适用于iOS,但KeyboardSpacer在Android上也可以使用。 - Christoph Göttert
它在Android上的表现非常糟糕,有时会添加太多的空格。 - cort

0

我使用了WebView.onTouchStart和ScrollView.scrollTo。这对我来说非常有效。

import { useRef } from "react";
import {
  widthPercentageToDP as wp,
  heightPercentageToDP as hp
} from "react-native-responsive-screen";

const scrollRef = useRef();

const scrolldown = () => {
   scrollRef.current.scrollTo((wp("100%") * 2) / 3);
};

<ScrollView ref={scrollRef} >
...

<WebView onTouchStart={scrolldown} >
...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接