如何判断浏览器在运行时运行的React版本? [英] How can one tell the version of React running at runtime in the browser?
问题描述
是否可以在浏览器中了解React的运行时版本?
Is there a way to know the runtime version of React in the browser?
推荐答案
React.version
是您想要的.
不过(据我所知)它没有记录,因此它可能不是一个稳定的功能(即,虽然不太可能,但它可能会消失或在将来的发行版中更改).
It is undocumented though (as far as I know) so it may not be a stable feature (i.e. though unlikely, it may disappear or change in future releases).
示例 React
作为脚本导入的示例
Example with React
imported as a script
const REACT_VERSION = React.version;
ReactDOM.render(
<div>React version: {REACT_VERSION}</div>,
document.getElementById('root')
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="root"></div>
示例,其中 React
作为模块导入
Example with React
imported as a module
import React from 'react';
console.log(React.version);
很明显,如果将 React
作为模块导入,则它将不在全局范围内.上面的代码旨在与您应用的其余部分捆绑在一起,例如使用 webpack .如果在浏览器的控制台中使用它(实际上是使用裸导入),它将几乎永远无法工作.
Obviously, if you import React
as a module, it won't be in the global scope. The above code is intended to be bundled with the rest of your app, e.g. using webpack. It will virtually never work if used in a browser's console (it is using bare imports).
推荐使用第二种方法.大多数网站都会使用它. create-react-app 做到这一点(它使用的是 webpack 在幕后).在这种情况下, React
是经过封装的,通常在捆绑包之外(例如,在浏览器的控制台中)根本无法访问.
This second approach is the recommended one. Most websites will use it. create-react-app does this (it's using webpack behind the scene). In this case, React
is encapsulated and is generally not accessible at all outside the bundle (e.g. in a browser's console).
这篇关于如何判断浏览器在运行时运行的React版本?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!