简体   繁体   中英

How to use eventlisteners and functions from outside react components?

I have loaded a library (cordova) in my main index.html file. Then I added the eventlistener 'deviceready' on my document. Now how can I call this function and the related library inside a react component?

Html file:

<!DOCTYPE html>
<html>
  <head>
      <title>title</title>
  </head>
  <body>
    <div id="app"></div>
  </body>

<script type="text/javascript" src="cordova.js"></script>
<script>
  document.addEventListener('deviceready', onDeviceReady);

  // this is the function I want to call inside my component.
  // function onDeviceReady() {
  //   var rect = { x: 0, y: 0, width: window.innerWidth, height: window.innerHeight };
  //   cordova.plugins.camerapreview.startCamera(rect, 'back', true, true, true)
  //   cordova.plugins.camerapreview.show();
  // }
</script>

</html>

My react component:

import React, { Component } from 'react';

class Example extends Component {

   // Here I want to call my cordova actions inside the eventlistener

   render() {
     return (
       <div>
         <p>Example</p>
       </div>
     );
   }
}

export default Example;

By using Reacjs lifesycle is a proper way to add and remove events

So you can do something like this:

import React, { Component } from 'react';

class Example extends Component {

  componentDidMount() {
    document.addEventListener('deviceready', this.deviceReady);
  }

  componentWillUnmount() {
    document.removeEventListener('deviceready', this.deviceReady);
  }

  deviceReady () {
    // Do some stuff
  }

   render() {
     return (
       <div>
         <p>Example</p>
       </div>
     );
   }
}

export default Example;

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