在React Native中从WebView检测按钮单击 [英] Detect button click from WebView in React Native
问题描述
有人可以帮我解决如何在React Native中检测Webview按钮点击事件的问题吗?如下面的代码所示,我在我的WebView(index.html)中有一个Button,我想从React Native中检测click事件并执行onClick方法。我尝试了多种方法,但未能成功。非常感谢提前。
Can anyone please help me on how to detect Webview button click event in React Native? As shown in the code below, I have a Button in my WebView (index.html) for which i want to detect click event from React Native and execute the method onClick. I have tried multiple ways, but couldn't succeed. Thanks so much in Advance.
我的MyApp.js
my MyApp.js
import React from 'react';
import { AppRegistry, View, WebView, StyleSheet} from 'react-native'
export default class MyApp extends React.Component {
onClick = () => {
console.log('Button Clicked');
}
render() {
return (
<View style={styles.container}>
<WebView
style={styles.webView}
source={require('./index.html')}/>
</View>
);
}
};
let styles = StyleSheet.create({
container: {
flex: 1,
backgroundColor: '#fff',
},
webView: {
backgroundColor: '#fff',
height: 350,
}
});
my index.html
my index.html
<html>
<body>
<Button>Click Here</Button>
</body>
</html>
推荐答案
添加 window.postMessage( )
到你的页面文件, onMessage = {this.onMessage}
到你的React Native WebView组件。
Add window.postMessage()
to your page file and onMessage={this.onMessage}
to your React Native WebView component.
示例:
// index.html (Web)
...
<script>
window.postMessage("Sending data from WebView");
</script>
...
// MyWebView.js (React Native)
<WebView>
...
<WebView
ref="webview"
onMessage={this.onMessage}
/>
onMessage(data) {
//Prints out data that was passed.
console.log(data);
}
编辑:
工作示例:
Working example:
App.js
onMessage(m) {
alert(m.nativeEvent.data);
}
render() {
return(
<WebView
style={{ flex: 1 }}
source={{uri: 'http://127.0.0.1:8877'}} //my localhost
onMessage={m => this.onMessage(m)}
)
/>
}
index.html
index.html
<button>Send post message from web</button>
<script>
document.querySelector("button").onclick = function() {
console.log("Send post message");
window.postMessage("Hello React", "*");
}
</script>
希望有所帮助
这篇关于在React Native中从WebView检测按钮单击的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!