[英]What is the best way format injected javascript in react-native?
Is there an efficient way format large amounts of injected javascript strings and retain type completion + testable functionality for react-native-webview?是否有一种有效的方式格式化大量注入的 javascript 字符串并为 react-native-webview 保留类型完成 + 可测试功能?
For react-native, the react-native-webview library allows communication across a native WebView and react-native.对于 react-native, react-native-webview库允许跨原生 WebView 和 react-native 进行通信。 This requires injection of javascript in string format to customize what is communicated and how user interactions are processed.
这需要以字符串格式注入 javascript 以自定义通信内容以及处理用户交互的方式。
This injection can quickly get messy, unreadable, or have small bugs that are hard to test when a bunch of functionality needs to be combined.当需要组合一堆功能时,这种注入很快就会变得混乱、不可读,或者存在难以测试的小错误。
Does anyone have a better scalable solution for this?有没有人有更好的可扩展解决方案?
My requirements for injectableStrings (that affect the Webview DOM)我对injectableStrings的要求(影响Webview DOM)
The react-native-webview docs give simplified references to javascript in string format which do not have syntax or type completions. react-native-webview 文档以字符串格式提供了对 javascript 的简化引用,这些格式没有语法或类型完成。
Current approach and Answer当前的方法和答案
Example例子
Browser.injectableJavascript.ts Browser.injectableJavascript.ts
const registerPressHandler = () => {
const imgNodes = document.getElementsByTagName('img')
const linkNodes = document.getElementsByTagName('a')
// add callbacks etc...
}
// re-registers events whenever the document re-renders nodes...
const createObservers = () => {
const observer = new MutationObserver(mutations => {
mutations.forEach(mutation => {
// handle cases here...and rebind events to new nodes
registerPressHandler()
})
})
observer.observe(document.body, {
childList: true,
subtree: true,
})
}
export const browserInjection = `
${registerPressHandler.toString()};
// initialize web click handler
registerPressHandler()
${createObservers.toString()};
createObservers();
`
Browser.tsx浏览器.tsx
import React from 'react'
import Webview from 'react-native-webview'
import { browserInjection } from './Browser.injections'
const Browser = () => {
return <Webview injectedJavascript={browserInjection} />
}
export default Browser
Other ideas:其他想法:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.