我可以在View中使用WebView(本地反应)吗?

use*_*421 21 webview react-native

我正在尝试在View组件中使用WebView Component,用于我正在处理的反应本机应用程序.当我在View中嵌入WebView时,我没有看到我在WebView中显示的内容.这是本地反应的预期行为吗?

abe*_*rdi 25

您应该为webview指定宽度和高度.做如下:

render() {
return (
  <WebView
    source={{uri: 'https://github.com/facebook/react-native'}}
    style={{flex: 1}} // OR style={{height: 100, width: 100}}
  />
);}
Run Code Online (Sandbox Code Playgroud)

  • 父视图`View`也应该是`flex:1`:https://snack.expo.io/r1II-3jc- (5认同)

小智 20

当它嵌套在View组件中时,您需要将view和webview flex都设置为1.

例如. -

<View style={{flex:1}}>
    <WebView
      source={{ uri: url }}
      style={{flex:1}}
      />
</View>
Run Code Online (Sandbox Code Playgroud)

  • 我的5美分。我一直在尝试在我的应用程序中使用容器的通用样式。但我的容器样式包含 `alignItems` 属性,据我了解,该属性不适合 WebViews。当我切换到仅使用“flex:1”的简单样式时,WebView 出现了。 (2认同)

Aks*_*hav 7

请使用以下代码:

import React from 'react';
import {View, ImageBackground, StyleSheet} from 'react-native';
import { WebView } from 'react-native-webview';

export default class WebViewScreen extends React.Component {
    render(){
        return(
            <View style={styles.container}>
                <WebView 
                    source= {{uri: 'https://www.google.com'}}
                    style= {styles.loginWebView}
                />
            </View>
        );
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        justifyContent: 'flex-start',
        alignItems: 'stretch',
    },
    loginWebView: {
        flex: 1,
        marginTop: 30,
        marginBottom: 20
    }
});
Run Code Online (Sandbox Code Playgroud)

这段代码对我来说非常好,

在上述所有解决方案中,我观察到每个人都建议添加flex: 1到您的 webView 样式。

是的,这是正确的,但如果您想将 WebView 嵌套在 View 中,则需要精确指定父视图的样式。

所以,我设置了justifyContent: 'flex-start'以便垂直 WebView 将从我的屏幕顶部开始和alignItems: 'stretch'以便 WebView 将在水平方向上全部可用

因为我们使用 justifyContent 来指定主轴对齐方式,使用 alignItems 来指定次轴对齐方式,默认 flexDirection 是 column。

要获取有关如何安装 react-native-webview 的更多信息,请参阅以下链接:https : //github.com/react-native-community/react-native-webview/blob/master/docs/Getting-Started.md