我有 RN <=> Webview 正在运行
- webview 订阅“getFoo”消息
- webview 将 foo 值设置为“woo”(通过断点我可以确认 foo 值已更新)
- RN 向 webview 发送“getFoo”消息:给我 foo 的值
- webview 通过回调得到 RN 请求的通知,这里 foo 的值是空的!为什么?
- webview 将 foo 值(空)发送给 RN
下面是webview部分
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>
)
}