ReactNative 使用WebView的大坑

  • Post author:
  • Post category:其他


ReactNative项目中需要用到WebView,初次使用WebView遇到的坑

先上代码:

import React, { Component} from “react”

import {WebView} from “react-native-webview”

import { View, Text } from “react-native”

class MyWeb extends Component {

render() {

return(

<View style={

{overflow: ‘hidden’}}>

<Text>开始</Text>

<WebView

source={

{html:”<h1 style=’color:#ff0000′>Hello word</h1>”}}

style={

{marginTop:30,flex:1}}

originWhitelist={[‘*’]}

onNavigationStateChange={this.onNavigationStateChange}

></WebView>

<Text>结束</Text>

</View>

)

}

}

要在RN中实现WebView,首先需要下载

react-native-webview组件,安装方法:

yarn add react-native-webview    或者  npm install –save react-native-webview

后直接运行项目,坑就来:

一、项目报:Error:crypto.getRandomValues() not supported.图如下:

这错误提示缺少包,根据错误提示的地址,发现需要下载react-native-get-random-values这个组件,不明白为什么下载web-view的时候不自动下载。添加方法:

npm install –save react-native-get-random-values

添加成功后,运行项目,发现还是报同样的问题。这就难受了,百度也找不到结果,后来在webView的Issues才找到解决办法,原来需要在项目的index.js中引入刚才添加的包,我的index.js如下:

import “react-native-get-random-values”

import {AppRegistry} from ‘react-native’;

import App from ‘./view/Analysis/AnalysisWebView’;

import {name as appName} from ‘./app.json’;

AppRegistry.registerComponent(appName, () => App);

再次运行,终于不报错了。

但是,错误是不报错了,但是,我的WebView显示不出来啊,就跟没有这个组件一样,效果:

如图,WebView的前后信息都出来了,就是WebView没有任何的表示,各种百度,查找都没有找到解决办法,

后来,终于找到问题了,解决这个问题就是



<WebView>组件不能被其他组件包裹!



,坑啊,没有任何一个地方说明这个问题,改正之后,代码:

import React, { Component} from “react”

import {WebView} from “react-native-webview”

import { View, Text, Button, StyleSheet } from “react-native”

class MyWeb extends Component {

render() {

return(

<WebView

source={

{html:”<h1 style=’color:#ff0000′>Hello word</h1>”}}

style={

{marginTop:30,flex:1}}

originWhitelist={[‘*’]}

onNavigationStateChange={this.onNavigationStateChange}

></WebView>

)

}

}

一个简单的WebView这才起来



版权声明:本文为zhoufei3813原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。