React Native WebView

17 Mar 2025 | 阅读 2 分钟

React Native WebView 是一个用于加载 Web 内容或网页的组件。 WebView 组件是从核心 react-native 库导入的。现在,WebView 已经从内置的核心 react-native 中移除,并放置在 react-native-webview 库中。

注意:建议使用 React Native WebView 导入 react-native-webview 或 react-native-community 库。

WebView 的 Props

sourceinjectJavaScriptinjectedJavaScriptonError
onLoadonLoadEndonLoadStartonMessage
originWhitelistrenderErrorstyleuserAgent
htmlurlgeolocationEnabledscrollEnabled
contentInsetbouncesallowFileAccessnativeConfig

WebView 内容的类型

将 HTML 代码显示为字符串: HTML 字符串代码传递到 source 属性内的 html prop 中。

显示内部网页: 在目录中创建一个内部网页,并在 source 属性中传递其完整路径。

显示远程网页: 使用带有 source 属性的 uri 标签加载远程网页。

React Native WebView 示例 1

在此示例中,我们将通过在 WebView 组件的 source prop 中传递其 URL 来加载网页。

App.js

React Native WebView

React Native WebView 示例 2

在此示例中,我们将从 react-native-webview 导入 WebView。

App.js

输出

React Native WebView

注意:如果您收到模块 react-native-webview 在模块映射 react native 中不存在的错误消息。然后确保您安装了以下库

  • npm install -g yarn
  • yarn add react-native-webview
  • react-native link react-native-webview

下一个主题ProgressBarAndroid