反应组件中的 onDeviceReady 事件侦听器
onDeviceReady event listener in react component
在我的 React 应用程序中,我尝试使用 Cordova 插件 (cordovo-plugin-device) 来获取用户的设备版本,如下所示
class LogoHeader extends React.Component {
componentDidMount () {
window.addEventListener('deviceready', this.onDeviceReady)
}
onDeviceReady () {
console.log(device.cordova)
}
render () {
...
}
}
但由于某种原因,deviceready
事件从未被触发。我错过了什么吗?有没有更好的方法来监听 DOM 反应中的事件?
根据 Cordova docs and this SO answer 你应该在你的入口文件中添加监听器(可能 index.js
)
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
const startApp = () => {
console.log(device.cordova)
ReactDOM.render(
<App />,
document.getElementById('root')
);
}
if(!window.cordova) {
startApp()
} else {
document.addEventListener('deviceready', startApp, false)
}
您还可以将 device.cordova
作为 props 传递给 App
,这样您就可以在其他组件中访问它。
...
ReactDOM.render(
<App device={device
? device.cordova
: null}/>,
document.getElementById('root')
);
...
在我的 React 应用程序中,我尝试使用 Cordova 插件 (cordovo-plugin-device) 来获取用户的设备版本,如下所示
class LogoHeader extends React.Component {
componentDidMount () {
window.addEventListener('deviceready', this.onDeviceReady)
}
onDeviceReady () {
console.log(device.cordova)
}
render () {
...
}
}
但由于某种原因,deviceready
事件从未被触发。我错过了什么吗?有没有更好的方法来监听 DOM 反应中的事件?
根据 Cordova docs and this SO answer 你应该在你的入口文件中添加监听器(可能 index.js
)
import React from 'react';
import ReactDOM from 'react-dom';
import App from './App';
const startApp = () => {
console.log(device.cordova)
ReactDOM.render(
<App />,
document.getElementById('root')
);
}
if(!window.cordova) {
startApp()
} else {
document.addEventListener('deviceready', startApp, false)
}
您还可以将 device.cordova
作为 props 传递给 App
,这样您就可以在其他组件中访问它。
...
ReactDOM.render(
<App device={device
? device.cordova
: null}/>,
document.getElementById('root')
);
...