简体   繁体   中英

React Native Expo WebView Communication

I'm working on an app where I need to interact with a webview. Essentially I need to call a function in the webview and capture (somehow) what it returns.

Essentially the parent class has a button. This buttons triggers a function called in the child class which sends a message to the webview. The webview then sends a message back which triggers the onMessage() function. So my question basically is, How can the parent function testFunc() access the data the webview returned.

Here is a simplified example of the child class.

export default class Child extends Component {
  sendMessageToWebView = () => {
    this.webview.postMessage("Hello WebView, from React Native");
  }

  html = () => {
    `<body>
     <script>
       document.addEventListener("message", function(data) {
         console.log(data);
         window.postMessage("Hello from WebView :)");
       });
     </script>
    </body>`
  }

  onMessage = (data) => {
    console.log(data.nativeEvent.data);
    return data.nativeEvent.data;
  }


  render() {
    return (
      <View>
        <WebView
          ref={(view) => { this.webview = view; }}
          source={{ html() }}
          onMessage={this.onMessage}
        />
      </View>
    );
  }
}

Here is an example of the parent class

export default class Parent extends Component {
  testFunc = () => {
    this.child.sendMessageToWebView();
  }

  render() {
    return (
      <View>
         <Button onPress={this.testFunc} title={'Test'} />
         <Child ref={child => {this.child = child}} />
      </View>
    );
  }
}

I have thought about using states, but I end up with a similar problem. How does the parent function know when the state has been changed in the child class.

Any help would be greatly appreciated thanks.

You can set the state in the child class after the data has been received. We can then call a function sendData in the parent to update the state of that parent class with the new data.

export default class Child extends Component { 
  constructor(props) {
    super(props);
    this.state = {
      data: null,
    };
  }

  ...

  onMessage = (data) => {
    const data = data.nativeEvent.data;
    this.setState({ data: data }, sendToParent);
  }

  sendToParent = () => {
    this.props.sendData(this.state.data);
  }
  ...

You can then access the state of the child class from the parent class this.state.data

export default class Parent extends Component {
  constructor(props) {
    super(props);
    this.state = {
      data: null,
    };
  }

 ...

 sendData = (data) => {
   this.setState({ data: data });
 }

 ...

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM