javascript - 如何使用外部 react 组件的事件监听器和函数?

标签 javascript cordova reactjs

我已经在我的主index.html 文件中加载了一个库(cordova)。然后我在文档中添加了事件监听器“deviceready”。现在我如何在 react 组件中调用这个函数和相关的库?

HTML 文件:

<!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>

我的 react 组件:

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;

最佳答案

通过使用Reacjs lifesycle是添加和删除事件的正确方法

所以你可以这样做:

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;

关于javascript - 如何使用外部 react 组件的事件监听器和函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40482916/

相关文章:

javascript - 使用 PHP、JQuery、Ajax 将电子邮件添加到 MySQL 数据库

javascript - 站点加载后向 Piwik 添加自定义 session 参数

cordova - 在 Visual Studio 2015 中开发 Cordova 项目

javascript - 访问 jQuery 内部的 javascript native "this"

Javascript map 返回函数

javascript - cordova s​​etTimeout 函数

node.js - 如何在 cordova 应用程序中配置 node.js 路由

javascript - 当用户直接点击需要来自另一个组件的 id 的 url 时,React 中的路由问题

javascript - 如何在 setState 回调之外将 .map() val 和 key 渲染为 prop

javascript - ReactJs 添加事件类到按钮