RN webview 和JS如何通信?

来源:14-6 打包发布React Native项目【收获果实】

CrazyCodeBoy

2019-12-16

消息通信的几种形式:

  • React Native -> Web :可以使用injectedJavaScript propinjectJavaScript method
  • Web -> React Native :可以使用postMessage method + onMessage prop

React Native -> Web

使用injectedJavaScript prop

import React, { Component } from 'react';
import { View } from 'react-native';
import { WebView } from 'react-native-webview';

export default class App extends Component {
  render() {
    const runFirst = `
      document.body.style.backgroundColor = 'red';
      setTimeout(function() { window.alert('hi') }, 2000);
      true; // note: this is required, or you'll sometimes get silent failures
    `;
    return (
      <View style={{ flex: 1 }}>
        <WebView
          source={{
            uri:
              'https://github.com/react-native-community/react-native-webview',
          }}
          injectedJavaScript={runFirst}
        />
      </View>
    );
  }
}

使用injectedJavaScript method

import React, { Component } from 'react';
import { View } from 'react-native';
import { WebView } from 'react-native-webview';

export default class App extends Component {
  render() {
    const run = `
      document.body.style.backgroundColor = 'blue';
      true;
    `;

    setTimeout(() => {
      this.webref.injectJavaScript(run);
    }, 3000);

    return (
      <View style={{ flex: 1 }}>
        <WebView
          ref={r => (this.webref = r)}
          source={{
            uri:
              'https://github.com/react-native-community/react-native-webview',
          }}
        />
      </View>
    );
  }
}

Web -> React Native

需要借助window.ReactNativeWebView.postMessage method 与 onMessage prop来实现:

import React, { Component } from 'react';
import { View } from 'react-native';
import { WebView } from 'react-native-webview';

export default class App extends Component {
  render() {
    const html = `
      <html>
      <head></head>
      <body>
        <script>
          setTimeout(function () {
            window.ReactNativeWebView.postMessage("Hello!")
          }, 2000)
        </script>
      </body>
      </html>
    `;

    return (
      <View style={{ flex: 1 }}>
        <WebView
          source={{ html }}
          onMessage={event => {
            alert(event.nativeEvent.data);
          }}
        />
      </View>
    );
  }
}

参考:

写回答

2回答

慕粉7742191

2022-04-29

我想问一下,react-native项目如何使用antd-mobile

0
0

CrazyCodeBoy

提问者

2019-12-16

如上。

0
0

RN入门到进阶,打造高质量上线App

解锁React Native开发应用新姿势,React Native新版本热门技术

3144 学习 · 3241 问题

查看课程