(React Native)将本地HTML文件加载到WebView中

时间:2017-03-17 07:09:26

标签: webview react-native

我尝试将本地.html文件加载到 React Native 中的WebView

// load local .html file
const PolicyHTML = require('./Policy.html');

// PolicyHTML is just a number of `1`
console.log('PolicyHTML:', PolicyHTML);

// will cause an error: JSON value '1' of type NSNumber cannot be converted to NSString
<WebView html={PolicyHTML} />

.html文件应该作为字符串读取,而不是作为资源代表读取。

如何在React Native中将.html文件加载到WebView

顺便说一下,来自require()的那些资源代表的类型是什么?是number吗?

5 个答案:

答案 0 :(得分:23)

试一试:

const PolicyHTML = require('./Policy.html');

<WebView
  source={PolicyHTML}
  style={{flex: 1}}
 />

答案 1 :(得分:4)

我在这篇文章中搜索了如何加载静态html。
如果您使用例如API检索html代码,则可以通过以下方式呈现WebView:

<WebView
    originWhitelist={['*']}
    source={{ html: html, baseUrl: '' }}
/>

请注意,originWhitelist是必需的,如documentation所述:

  

请注意,静态html将需要为   例如[[*“]。

答案 2 :(得分:2)

<View style={{flex: 1}}>
    <WebView
      style={{flex: 1}}
      source={require("./resources/index.html")}
    />
</View>

要制作WebView,父级必须具有维度或弹性:1。我们可以将WebView设置为flex:1,以便填充父级。

答案 3 :(得分:0)

试试这个:

  • 在项目中添加 .html 文件。
  • 在要使用WebView Component

    的文件中写下这样的代码行

    const OurStoryHTML = require ('./OurStory.html')

  • <WebView source={OurStoryHTML} style={{flex: 1, marginTop : 44}} />

它可能对你有帮助。

答案 4 :(得分:0)

首先,请从react-native忘掉Webview,因为它将在下一个版本中弃用,您可以看到Load Local HTML File or URL in React Native using react-native-webview。因此,我在项目中使用了react-native-webview,它现在可以正常工作。

需要注意的地方:

  1. 您必须管理HTML文件的两个副本。
  2. 对于IOS,将副本放在Project> resources> index.html中。
  3. 对于Android,您需要将其放入project> android> app> src> main> assets> index.html

在加载Web视图时,尝试找到平台并使用像这样的else加载。

if(isAndroid){
  return (
      <WebView
        style={{flex: 1}}
        originWhitelist={['*']}
        source={{uri:'file:///android_asset/index.html'}}
        style={{ marginTop: 20 }}
        javaScriptEnabled={true}
        domStorageEnabled={true}
      />
  )
}else{
  return(
    <WebView
      style={{flex: 1}}
      originWhitelist={['*']}
      source={'./resources/index.html'}
      style={{ marginTop: 20 }}
      javaScriptEnabled={true}
      domStorageEnabled={true}
    />
  );
}