在React Native中从WebView检测按钮单击

1 javascript webview reactjs react-native create-react-app

谁能帮我了解如何在React Native中检测Webview按钮单击事件吗?如下面的代码所示,我在WebView(index.html)中有一个Button,我想为其检测React Native的click事件并执行onClick方法。我尝试了多种方法,但未能成功。非常感谢您。

我的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,
}
});
Run Code Online (Sandbox Code Playgroud)

我的index.html

<html>
<body>
    <Button>Click Here</Button>
</body>
</html>
Run Code Online (Sandbox Code Playgroud)

sou*_*tot 6

添加window.postMessage()到页面文件和onMessage={this.onMessage}React Native WebView组件。

例:

// 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);
}
Run Code Online (Sandbox Code Playgroud)

编辑:工作示例:

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)} 
   )
/>
}
Run Code Online (Sandbox Code Playgroud)

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>
Run Code Online (Sandbox Code Playgroud)

希望能帮助到你