react-native 与HTML交互

使用框架 react-native-webview

安装 react-native-webview

yarn add react-native-webview

在放在根目录下,创建一个.bundle文件,将html、静态资源、css放到bundle里面如图


截屏2022-10-24 14.41.03.png
截屏2022-10-24 14.41.15.png

1.引入

import WebView from 'react-native-webview'

2.创建web 增加属性 originWhitelist={['*']}//解决iOS无法打开bundle里面的html问题 中文乱码显示的问题
onMessage 接受来自HTML的消息
使用this.webview.postMessage(JSON.stringify(data))给HTML发送消息

render() {
        let source = (Platform.OS === 'android' ? 'file:///android_asset/' : '') + `Static.bundle/index.html`;
        return (
             {
                    console.log('webview onLoad')
                }}
                onLoadEnd={() => {
                    console.log('webview onLoadEnd')
                }}
                onLoadStart={() => {
                    console.log('wenview onLoadStart')
                }}
                onMessage={event => {
                    console.log('===>接收到的消息', event.nativeEvent.data)
                    this.onMessageHandle(event.nativeEvent.data)
                    // 发送消息给HTML
                    this.sendMessageToHtml(event.nativeEvent.data)
                }}
                originWhitelist={['*']}//解决iOS无法打开bundle里面的html问题 中文乱码显示的问题
                javaScriptEnabled={true}
                ref={webview => this.webview = webview}

            />
        )
    }
}

3.html改造
在js里面增加方法,使用此方法向react-native传递消息

 window.ReactNativeWebView.postMessage()

接收来react-native的数据 最好两个都写上

window.addEventListener('message', function (e) {//注册事件 接收数据

        const message = e.data;//字符串类型

        console.log('WebView message:', message);

        alert(message);

    })
    document.addEventListener('message', function (e) {//注册事件 接收数据

        const message = e.data;//字符串类型

        console.log('WebView message:', message);

        alert(message);

    })

完整react代码

import React, { Component } from 'react'
import { StyleSheet, Dimensions, NativeModules, NativeEventEmitter,Alert } from 'react-native'
import WebView from 'react-native-webview'
const CalendarManager = NativeModules.CalendarManager
//接收来自原生app的消息
const calendarManagerEmitter = new NativeEventEmitter(CalendarManager);
const subscription = calendarManagerEmitter.addListener(
    'EventReminder',
    (reminder) => {
        console.log("===>接收到来自原生app的消息", reminder.name),
        Alert.alert(reminder.name)
    }

);
export default class MyWebview extends Component {
    constructor() {
        super()
        // this.sendMessageToHtml = this.sendMessageToHtml.bind(this)
    }
    // sendMessageToHtml = (data)=>{
    //     setTimeout(() => {
    //         console.log('===>需要传送的data',data)
    //         this.webview.postMessage(JSON.stringify(data))   
    //     }, 2000);
    // }
    // onMessageHandle =(data)=>{
    //     console.log('===>',data)
    //     let obj = JSON.parse(data)
    //     console.log('===>obj',obj)
    //     if(obj.home === 'userCamara'){
    //         this.props.navigation.navigate('swiper')
    //     }
    // }
    //发送消息给HTML
    sendMessageToHtml = (data) => {

        setTimeout(() => {
            console.log('===>需要传送的data', data)
            this.webview.postMessage(JSON.stringify(data))   
        }, 2000);
    }
    //HTML 向 react-native发送消息
    onMessageHandle = (data) => {
        console.log('===>', data)
        let obj = JSON.parse(data)
        console.log('===>obj', obj)
        // if(obj.home === 'userCamara'){
        if (obj.type === '0') {
            this.props.navigation.navigate(obj.home)
        } else {
            console.log('===>type', obj.type)
            this.sendMessageToOC(obj)
        }

        // }
    }
    //发消息给OC
    sendMessageToOC = (data) => {
        CalendarManager.addDic('生日派对',
            data,
            (error, events) => {
                if (error) {
                    // alert(error)
                } else {
                    // alert(events)
                }

            }

        )
    }

    render() {
        let source = (Platform.OS === 'android' ? 'file:///android_asset/' : '') + `Static.bundle/index.html`;
        return (
             {
                    console.log('webview onLoad')
                }}
                onLoadEnd={() => {
                    console.log('webview onLoadEnd')
                }}
                onLoadStart={() => {
                    console.log('wenview onLoadStart')
                }}
                onMessage={event => {
                    console.log('===>接收到的消息', event.nativeEvent.data)
                    this.onMessageHandle(event.nativeEvent.data)
                    this.sendMessageToHtml(event.nativeEvent.data)
                }}
                originWhitelist={['*']}//解决iOS无法打开bundle里面的html问题 中文乱码显示的问题
                javaScriptEnabled={true}
                ref={webview => this.webview = webview}

            />
        )
    }
}

const styles = StyleSheet.create({
    container: {
        flex: 1,
        width: Dimensions.get('window').width,
        height: Dimensions.get('window').height
    }
})

html代码





    
    
    
    Document
    
    



    

css

  
.bodyContainer{
    display: flex;
    flex-direction: column;
    justify-content: center;
    align-items: center;
}
.itemContainer{
    display: flex;
    flex-direction: row;
    justify-content: start;
    flex-wrap: wrap;
}
.itemStyles{
    display: flex;
    flex-direction: column;
    width: 23vw;
    height: 110px;
    justify-content: center;
    align-items: center;
    text-align: center;
    font-size: 12px;
}

react-native 与原生OC的交互:https://www.jianshu.com/p/5a5d3995ae31

你可能感兴趣的:(react-native 与HTML交互)