在React原生WebView中,要将参数传递给外部JavaScript文件中的函数,可以通过以下步骤实现:
import React from 'react';
import { WebView } from 'react-native';
const MyWebView = ({ parameter }) => {
const webViewRef = React.useRef(null);
React.useEffect(() => {
if (webViewRef.current) {
webViewRef.current.postMessage(parameter);
}
}, [parameter]);
return (
<WebView
ref={webViewRef}
source={{ uri: 'your_webpage_url' }}
onMessage={(event) => {
const data = event.nativeEvent.data;
// Handle the data received from JavaScript function
}}
/>
);
};
export default MyWebView;
window.postMessage
方法将参数传递给React Native应用。function sendDataToNative(parameter) {
window.postMessage(parameter);
}
import WebKit
class ViewController: UIViewController, WKScriptMessageHandler {
override func viewDidLoad() {
super.viewDidLoad()
let contentController = WKUserContentController()
contentController.add(self, name: "messageHandler")
let configuration = WKWebViewConfiguration()
configuration.userContentController = contentController
let webView = WKWebView(frame: view.bounds, configuration: configuration)
view.addSubview(webView)
// Load your web page
let url = URL(string: "your_webpage_url")
let request = URLRequest(url: url!)
webView.load(request)
}
// Handle messages received from JavaScript
func userContentController(_ userContentController: WKUserContentController, didReceive message: WKScriptMessage) {
if message.name == "messageHandler" {
let parameter = message.body as? String
// Handle the parameter received from JavaScript function
}
}
}
通过上述步骤,你可以在React原生WebView中将参数传递给外部JavaScript文件中的函数,并在Xcode中接收和处理这些参数。请注意,这只是一个基本示例,具体实现可能会根据你的项目结构和需求有所不同。
领取专属 10元无门槛券
手把手带您无忧上云