1.封裝工具類
utils/jump.js
import Taro from '@tarojs/taro' const PAGE_WEBVIEW = '/pages/webview/webview' /** * // NOTE 后端返回的 url 可能是網頁鏈接,需要在 webview 中打開 * 也可能是小程序自身的鏈接,只能用 navigate/redirect 之類的打開 * 就需要有個地方統一判斷處理 */ export default function jump(options) { const { url, title = '', payload = {}, method = 'navigateTo' } = options if (/^https?:\/\//.test(url)) { Taro[method]({ url: urlStringify(PAGE_WEBVIEW, { url, title }) }) } else if (/^\/pages\//.test(url)) { // TODO H5 不支持 switchTab,暫時 hack 下 if (process.env.TARO_ENV === 'h5' && method === 'switchTab') { Taro.navigateBack({ delta: Taro.getCurrentPages().length - 1 }) setTimeout(() => { Taro.redirectTo({ url }) }, 100) return } Taro[method]({ url: urlStringify(url, payload) }) } } function urlStringify(url, payload, encode = true) { const arr = Object.keys(payload).map(key => `${key}=${encode ? encodeURIComponent(payload[key]) : payload[key]}` ) // NOTE 注意支付寶小程序跳轉鏈接如果沒有參數,就不要帶上 ?,否則可能無法跳轉 return arr.length ? `${url}?${arr.join('&')}` : url }
2.webview 頁面
src/pages/webview/webview.js
import Taro, { Component } from '@tarojs/taro' import { View, WebView } from '@tarojs/components' /** * // NOTE Taro 的 RN 端還未提供 WebView 組件,可以引入原生組件來解決 * (備注:Taro v1.2.16 已支持,這塊代碼還是保留作為演示) * * Taro 有開啟了 tree shaking,對於未用到的內容編譯時會自動去除 * 因此可以把相應端的內容都 import 進來,再根據環境進行調用即可 * * 另外 1.2.17 版本有提供了統一接口方式 https://nervjs.github.io/taro/docs/envs.html * 可以參考 ./src/pages/user-login 中的實現 */ import WebViewRN from './rn' import './webview.scss' export default class extends Component { config = { navigationBarTitleText: '' } url = '' title = '' componentWillMount() { this.url = decodeURIComponent(this.$router.params.url || '') this.title = decodeURIComponent(this.$router.params.title || '') Taro.setNavigationBarTitle({ title: this.title }) } render () { return ( <View className='webview'> {/* // NOTE 編譯時只會保留相應端的內容,因此非 RN 端時不會編譯 WebViewRN */} {process.env.TARO_ENV === 'rn' ? <WebViewRN src={this.url} /> : <WebView src={this.url} /> } </View> ) } }
src/pages/webview/webview.scss
.webview { height: 100%; }
src/pages/webview/rn/index.js
/** * React Native 原生組件 */ import Taro, { Component } from '@tarojs/taro' import { WebView } from 'react-native' export default class WebViewRN extends Component { render() { return ( <WebView style={{ height: '100%' }} originWhitelist={['*']} source={{ uri: this.props.src }} /> ) } }
.