React Native和Webview通信,如何从RN调用react函数? [英] React Native and webview communication, how to call react function from RN?

查看:536
本文介绍了React Native和Webview通信,如何从RN调用react函数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在运行RN< => Webview

I have RN <=> Webview running

  • webview订阅"getFoo"消息
  • webview将foo值设置为"woo"(有了断点,我可以确认foo值已更新)
  • RN向Webview发送"getFoo"消息:给我foo的值
  • webview通过回调获得RN请求的通知,此处foo值为空!为什么?
  • webview将foo值(空)发送给RN

下面是网络视图部分

import _ from "lodash"
import React, {
  useState,
  useContext,
  useEffect,
  useReducer,
  useCallback,
  useRef
} from "react"

const EventEmitter = {
  _events: {},
  dispatch: function(event, data) {
    if (!this._events[event]) return
    this._events[event].forEach(callback => callback(data))
  },
  subscribe: function(event, callback) {
    if (!this._events[event]) this._events[event] = []
    this._events[event].push(callback)
  }
}

window.EventEmitter = EventEmitter

// webview
const WebviewApp = props => {
  // https://codesandbox.io/s/lively-breeze-l9z82

  const [foo, setFoo] = useState('')

  useEffect(() => {


    EventEmitter.subscribe("getFoo", event => {
      sendFoo()
     // here foo is empty! 
    })
  }, [])

  const sendFoo = () => {
    window.ReactNativeWebView.postMessage(foo)
  }

  const handleClick = () => {
    setFoo("woo")
  }

  return (
    <div className="App">
      <button onClick={handleClick} />
    </div>
  )
}

以下是RN部分

import {WebView} from 'react-native-webview'

const RNApp = props => {
  const webEl = useRef(null)

  getFooFromWebview = () => {
    const run = `
window.EventEmitter.dispatch('getFoo', {});
`
    webEl.current.injectJavaScript(run)
  }


  const uri = "server url which hosts the webview code"
  return (
    <View style={{flex: 1}}>
      <TouchableOpacity onPress={getFooFromWebview}>
        <Text>click</Text>
      </TouchableOpacity>

      <WebView
        ref={webEl}
        javaScriptEnabledAndroid
        source={{uri}}
        onMessage={(event) => {
          console.log(event)
        }}
        data={props.data}
      />
    </View>
  )

}

推荐答案

useEffect将不会更新,因为您要传递一个空数组.只需通过状态foo,然后您将得到更新:

useEffect will not update since you're passing an empty array. Just pass the state foo and then you'll get update:

useEffect(() => {
    EventEmitter.subscribe("getFoo", event => {
      sendFoo()
    })
  }, ['foo']) // re-run useEffect on 'foo' state change

这篇关于React Native和Webview通信,如何从RN调用react函数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆