【问题标题】:onDeviceReady event listener in react component反应组件中的 onDeviceReady 事件监听器
【发布时间】:2019-01-15 07:04:59
【问题描述】:

在我的 react 应用程序中,我正在尝试使用 Cordova 插件 (cordovo-plugin-device) 来获取用户的设备版本,如下所示

class LogoHeader extends React.Component {
  componentDidMount () {
    window.addEventListener('deviceready', this.onDeviceReady)
  }
  onDeviceReady () {
    console.log(device.cordova)
  }
  render () {
    ...
  }
}

但由于某种原因,deviceready 事件永远不会被触发。我错过了什么吗?有没有更好的方法在 react 中监听 DOM 事件?

【问题讨论】:

    标签: reactjs cordova cordova-plugins react-dom


    【解决方案1】:

    根据Cordova docsthis 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 作为道具传递给App,以便您可以在其他组件中访问它。

    ...
    ReactDOM.render(
          <App device={device
             ? device.cordova
             : null}/>,
          document.getElementById('root')
        );
    ...
    

    【讨论】:

      猜你喜欢
      • 2018-10-18
      • 1970-01-01
      • 2016-04-15
      • 1970-01-01
      • 2020-12-27
      • 2019-09-17
      • 2019-08-12
      • 2019-12-08
      • 2022-11-04
      相关资源
      最近更新 更多