我有一個簡單的網站,帶有切換某些資料的切換功能。
<body>
<h1>customerType: <span id="h1_element"></span></h1>
<script>
let customerType = "Public"
function toggle(){
customerType = (customerType === "Public") ? "Private" : "Public"
document.getElementById("h1_element").innerText = customerType;
}
toggle()
</script>
</body>
然后我有一個 react-native 應用程式可以切換資料并顯示新資料。
export default function Inject() {
const [customer, setCustomer] = React.useState('-');
const viewRef = React.useRef();
const postCustomer = () => viewRef.current.injectJavaScript('window.ReactNativeWebView.postMessage(customerType)');
const toggleCustomer = () => {
viewRef.current.injectJavaScript('toggle()');
}
return (
<SafeAreaView style={{ flex: 1, top: 50 }}>
<Text>WebView data: {customer}</Text>
<Button onPress={toggleCustomer} title="toggle webView data" />
<WebView
ref={viewRef}
source={{ uri: 'localhost' }}
onMessage={ event => setCustomer(event.nativeEvent.data) }
javaScriptEnabledAndroid={ true }
onl oadEnd={ postCustomer }
/>
</SafeAreaView>
);
}
我可以通過簡單地使用 refName.current.injectJavaScript('funcName()') 來訪問該函式,但是您如何訪問具有許多模塊的函式大專案,這些模塊具有自己的腳本檔案,甚至可能具有相同的函式名稱?
我想一種方法是使函式成為全域函式,然后通過 window.funcName() 訪問它,或者將它系結到按鈕元素,然后使用查詢選擇器找到按鈕,但是有沒有更直接的方法?
uj5u.com熱心網友回復:
window在每個功能中創建物件。是這樣的:
window.test = { foo: 'bar', print: () => console.log('foobar') }
或者也許是應用程式的一個頂級物件來保持清潔
window.myApp = {
first: { foo: 'bar', print: () => console.log('foobar') },
second: { foo: 'bar', print: () => console.log('foobar') }
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/534854.html
標籤:反应本机
上一篇:發布應用程式后如何更新持久資料?
