一、WebView介紹
React Native WebView是一個React組件,它用於嵌入第三方web應用程序(如h5遊戲),同時仍然可以完全訪問所有native功能,包括可調用本機功能的自定義JavaScript代碼。
WebView基於WebKit瀏覽器引擎,這也是現代Chrome、Safari和其它瀏覽器所使用的引擎。所以可以支持大多數的Web API 和特性。
WebView可以通過設置內聯樣式和props來進行自定義,可以使用CSS樣式文件,也支持引用複雜的HTML代碼。
二、WebView 基本使用
1.引入WebView組件:
import React, { Component } from 'react'; import { WebView } from 'react-native-webview';
2.使用WebView:
export default class MyApp extends Component { render() { return ( <WebView source={{uri: 'https://www.example.com'}} style={{ marginTop: 20 }} /> ); } }
在上面的代碼示例中,source是用於指定WebView要加載的web頁面或網址,style用於設置WebView的樣式。
3.可以在WebView內部定義一個HTML文件:
export default class MyApp extends Component { render() { return ( <WebView source={{html: '<h1>Hello world </h1>'}} style={{ marginTop: 20 }} /> ); } }
以上代碼相當於渲染一個WebView,HTML頭部是一個包含“Hello world”標題的h1標籤。渲染的頁面將顯示在WebView內部的屏幕上。
三、WebView高級用法
1.調用Web中的JavaScript函數
為了從WebView中調用JavaScript函數,我們可以使用WebView的注入JavaScript功能和onMessage屬性
以下是示例代碼:
import React, { Component } from 'react'; import { WebView, Alert } from 'react-native-webview'; import { Button } from 'react-native'; export default class MyApp extends Component { webview = null; constructor(props) { super(props); this.state = {}; } injectJS = () => { const script = "alert('調用Web中的JavaScript函數')"; this.webview.injectJavaScript(script); }; onMessage(event) { Alert.alert(event.nativeEvent.data); } render() { return ( <> <Button title="調用Web中的JavaScript函數" onPress={this.injectJS}/> <WebView ref={(ref) => { this.webview = ref; }} source={{uri: 'https://www.example.com'}} onMessage={this.onMessage} style={{ marginTop: 20 }} /> </> ); } }
2.實現WebView與React Native的相互通信
WebView通過onMessage屬性和postMessage方法來實現與React Native的通信。
以下是示例代碼:
import React, { Component } from 'react'; import { WebView } from 'react-native-webview'; import { Button } from 'react-native'; export default class MyApp extends Component { constructor(props) { super(props); this.state = { count: 0 }; } onMessage(event) { const { type, data } = JSON.parse(event.nativeEvent.data); if (type === 'INCREMENT') { this.setState({ count: this.state.count + 1 }); } } onButtonPress() { this.refs.webview.postMessage(JSON.stringify({ type: 'INCREMENT' })); } render() { const html = ` <script> function onPress() { window.ReactNativeWebView.postMessage(JSON.stringify({ type: 'INCREMENT' })); } </script> <button onclick="onPress()">Increment</button> <p>Count: ${this.state.count}</p> `; return ( <> <Button title="增加" onPress={() => this.onButtonPress()} /> <WebView ref="webview" source={{ html: html }} onMessage={(event) => this.onMessage(event)} /> </> ); } }
以上代碼中,WebView通過postMessage方法向React Native發送一個json格式的數據,React Native 通過onMessage屬性來接收數據,同時WebView在相應的成功後展示具體數據。
總結
通過該文,我們了解了React Native WebView組件的基本使用和高級用法。在實際開發中,我們可以根據具體的業務需求來選擇使用WebView的相應功能,以達到更好的用戶體驗。
原創文章,作者:UNDOY,如若轉載,請註明出處:https://www.506064.com/zh-hant/n/333130.html