所以,经过几天的挣扎,我已经解决了以下解决方案,我承认这有点晦涩,但效果很好(包括后退按钮、手势):
在 React Web 应用程序中,我通过全局 Window 对象保持 ReactRouter 历史对象可用。
import { useHistory } from 'react-router'
// ...
declare global {
interface Window {
ReactRouterHistory: ReturnType<typeof useHistory>
}
}
const AppContextProvider = props => {
const history = useHistory()
// provide history object globally for use in Mobile Application
window.ReactRouterHistory = history
// ...
}
在 React Native 移动应用程序中,我将自定义代码注入到 WebView,它利用历史对象进行导航,并且应用程序使用消息与此代码进行通信:
webViewScript.ts
// ...
export default `
const handleMessage = (event) => {
var message = JSON.parse(event.data)
switch (message.type) {
// ...
case '${MessageTypes.NAVIGATE}':
if (message.params.uri && message.params.uri.match('${APP_URL}') && window.ReactRouterHistory) {
const url = message.params.uri.replace('${APP_URL}', '')
window.ReactRouterHistory.push(url)
}
break
}
};
!(() => {
function sendMessage(type, params) {
var message = JSON.stringify({type: type, params: params})
window.ReactNativeWebView.postMessage(message)
}
if (!window.appListenersAdded) {
window.appListenersAdded = true;
window.addEventListener('message', handleMessage)
var originalPushState = window.history.pushState
window.history.pushState = function () {
sendMessage('${MessageTypes.PUSH_STATE}', {state: arguments[0], title: arguments[1], url: arguments[2]})
originalPushState.apply(this, arguments)
}
}
})()
true
`
intercom.ts(此处没有路由细节,仅用于通用通信)
import WebView, {WebViewMessageEvent} from 'react-native-webview'
import MessageTypes from './messageTypes'
export const sendMessage = (webview: WebView | null, type: MessageTypes, params: Record<string, unknown> = {}) => {
const src = `
window.postMessage('${JSON.stringify({type, params})}', '*')
true // Might fail silently per documentation
`
if (webview) webview.injectJavaScript(src)
}
export type Message = {
type?: MessageTypes,
params?: Record<string, unknown>
}
export type MessageHandler = (message: Message) => void
export const handleMessage = (handlers: Partial<Record<MessageTypes, MessageHandler>>) => (
(event: WebViewMessageEvent) => {
const message = JSON.parse(event.nativeEvent.data) as Message
const messageType = message.type
if (!messageType) return
const handler = handlers[messageType]
if (handler) handler(message)
}
)
export {default as script} from './webViewScript'
WebViewScreen.tsx
import {handleMessage, Message, script, sendMessage} from '../intercom'
// ...
const WebViewScreen = ({navigation, navigationStack}: WebViewScreenProps) => {
const messageHandlers = {
[MessageTypes.PUSH_STATE]: ({params}: Message) => {
if (!params) return
const {url} = params
const fullUrl = `${APP_URL}${url}`
navigationStack.push(fullUrl)
},
// ...
}
const uri = navigationStack.currentPath
// navigation solution using history object propagated through window object
useEffect(() => {
if (uri) {
sendMessage(webViewRef.current, MessageTypes.NAVIGATE, {uri})
}
}, [uri])
// this is correct! Source is never going to be updated, navigation is done using native history object, see useEffect above
// eslint-disable-next-line react-hooks/exhaustive-deps
const source = useMemo(() => ({uri}), [])
return (
<View
// ...
refreshControl={
<RefreshControl
// ...
/>
}
>
<WebView
source={source}
injectedJavaScript={script}
onMessage={handleMessage(messageHandlers)}
// ...
/>
</View>
)
}