从 Webview 在 React Native 中获取和传递变量
Getting and Passing variables inside React Native from Webview
我在我的 React Native 项目中使用 [react-native-webview][1]。我的 webview 有一个 javascript 数组,我需要获取这个数组并在一个菜单中显示值,比如这个幻灯片菜单:
https://raw.githubusercontent.com/instea/react-native-popup-menu/master/android.demo.gif
代码:
function WebViewPage(){
const html = `
<html>
<body>
<div id="reportContainer">here apear the content..</div>
<script>
var reportContainer = document.getElementById('reportContainer');
var pages = [];
reportContainer.getPages().then(function (reportPages) {
//HERE RETURN A LIST FROM PAGES FROM MY REPORT..
pages = reportPages;
});
</script>
</body>
</html>
`
return(
<Page>
<WebView source={{html:html}} />
</Page>
);
}
export default WebViewPage;
基本上我需要获取页面数组并将菜单放在页眉中。我在考虑使用钩子,但我不知道如何获得这个数组,有什么想法吗?谢谢你。
[1]: https://github.com/react-native-community/react-native-webview
您可以在 webview
组件上使用 onMessage
回调函数。
function WebViewPage(){
const html = `
<html>
<body>
<div id="reportContainer">here apear the content..</div>
<script>
var reportContainer = document.getElementById('reportContainer');
var pages = [];
reportContainer.getPages().then(function (reportPages) {
//HERE RETURN A LIST FROM PAGES FROM MY REPORT..
pages = reportPages;
window.postMessage(pages);
});
</script>
</body>
</html>
`
const onMessage(data) {
console.log(data);
}
return(
<Page>
<WebView onMessage={onMessage} source={{html:html}} />
</Page>
);
}
export default WebViewPage;
我在我的 React Native 项目中使用 [react-native-webview][1]。我的 webview 有一个 javascript 数组,我需要获取这个数组并在一个菜单中显示值,比如这个幻灯片菜单: https://raw.githubusercontent.com/instea/react-native-popup-menu/master/android.demo.gif
代码:
function WebViewPage(){
const html = `
<html>
<body>
<div id="reportContainer">here apear the content..</div>
<script>
var reportContainer = document.getElementById('reportContainer');
var pages = [];
reportContainer.getPages().then(function (reportPages) {
//HERE RETURN A LIST FROM PAGES FROM MY REPORT..
pages = reportPages;
});
</script>
</body>
</html>
`
return(
<Page>
<WebView source={{html:html}} />
</Page>
);
}
export default WebViewPage;
基本上我需要获取页面数组并将菜单放在页眉中。我在考虑使用钩子,但我不知道如何获得这个数组,有什么想法吗?谢谢你。 [1]: https://github.com/react-native-community/react-native-webview
您可以在 webview
组件上使用 onMessage
回调函数。
function WebViewPage(){
const html = `
<html>
<body>
<div id="reportContainer">here apear the content..</div>
<script>
var reportContainer = document.getElementById('reportContainer');
var pages = [];
reportContainer.getPages().then(function (reportPages) {
//HERE RETURN A LIST FROM PAGES FROM MY REPORT..
pages = reportPages;
window.postMessage(pages);
});
</script>
</body>
</html>
`
const onMessage(data) {
console.log(data);
}
return(
<Page>
<WebView onMessage={onMessage} source={{html:html}} />
</Page>
);
}
export default WebViewPage;