[英]How to use eventlisteners and functions from outside react components?
I have loaded a library (cordova) in my main index.html file. 我已经在主index.html文件中加载了一个库(cordova)。 Then I added the eventlistener 'deviceready' on my document.
然后,我在文档中添加了事件监听器“ deviceready”。 Now how can I call this function and the related library inside a react component?
现在如何在React组件中调用此函数和相关库?
Html file: 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>
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 通过使用Reacjs lifesycle是添加和删除事件的正确方法
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;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.