ReactJS中的浏览器检测

ReactJS中的浏览器检测,第1张

ReactJS中的浏览器检测

您走在正确的轨道上,可以使用它们有条件地渲染jsx或帮助进行路由

我已经成功地使用了以下内容

// Opera 8.0+const isOpera = (!!window.opr && !!opr.addons) || !!window.opera || navigator.userAgent.indexOf(' OPR/') >= 0;// Firefox 1.0+const isFirefox = typeof InstallTrigger !== 'undefined';// Safari 3.0+ "[object HTMLElementConstructor]" const isSafari = /constructor/i.test(window.HTMLElement) || (function (p) { return p.toString() === "[object SafariRemoteNotification]"; })(!window['safari'] || (typeof safari !== 'undefined' && safari.pushNotification));// Internet Explorer 6-11const isIE = false || !!document.documentMode;// Edge 20+const isEdge = !isIE && !!window.StyleMedia;// Chrome 1 - 71const isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);// Blink engine detectionconst isBlink = (isChrome || isOpera) && !!window.CSS;

请注意,由于浏览器的更改,它们每个都有机会被弃用。

我在React中这样使用它们:

 content(props){    if(!isChrome){     return (      <Otherjsxelements/>     )    }    else {      return (      <Chromejsxelements/>     )    }  }

然后通过在我的主要组件中调用{this.Content()}来呈现不同浏览器特定的元素。

伪代码可能看起来像这样……(未经测试):

import React from 'react';const isChrome = !!window.chrome && (!!window.chrome.webstore || !!window.chrome.runtime);export default class Test extends React.Component {  content(){    if(isChrome){        return ( <div>Chrome</div>        )    } else {        return ( <div>Not Chrome</div>        )    }  }    render() {        return ( <div>Content to be seen on all browsers</div> {this.content()}        )    }}


欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/zaji/4901066.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-11-12
下一篇2022-11-12

发表评论

登录后才能评论

评论列表(0条)

    保存