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

李岡諭*_*李岡諭 21 webview react-native

我试图通过本地加载的.html文件到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} />
Run Code Online (Sandbox Code Playgroud)

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

如何将.html文件加载到WebViewReact Native中?


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

小智 24

试试吧:

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

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

  • 我想使用带有查询参数的 html: ?title=test&amp;sound=1 由于我们“需要”一个 html 文件,因此如何添加参数? (2认同)

Luc*_*nzo 8

我碰到这篇文章,寻找加载静态html。
如果使用例如API检索了html代码,则可以通过以下方式呈现WebView:

<WebView
    originWhitelist={['*']}
    source={{ html: html, baseUrl: '' }}
/>
Run Code Online (Sandbox Code Playgroud)

请注意,originWhitelist文档中所述,这是必需的:

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


小智 5

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

要制作 WebView,父级必须有一个维度或 flex:1。我们也可以将 WebView 设置为 flex: 1 以填充父级。