加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

React的exenv模块简析

发布时间:2020-12-15 07:39:03 所属栏目:百科 来源:网络整理
导读:问题1:为什么要使用exenv模块 React的ExecutionEnvironment模块被单独抽取出来,用于在其他组件或者包中使用,其简单用法如下: var ExecutionEnvironment = require('exenv');// You now have...ExecutionEnvironment.canUseDOM // is the DOM available?

问题1:为什么要使用exenv模块

React的ExecutionEnvironment模块被单独抽取出来,用于在其他组件或者包中使用,其简单用法如下:

var ExecutionEnvironment = require('exenv');
// You now have...
ExecutionEnvironment.canUseDOM             // is the DOM available? i.e window document etc. 
ExecutionEnvironment.canUseWorkers         // are Web Workers available?
ExecutionEnvironment.canUseEventListeners  // are Events available? i.e addEventListener etc.
ExecutionEnvironment.canUseViewport        // is there a viewport? i.e window.screen
在React的0.13中的ExecutionEnvironment包中包含了一个isInWorker属性,其值为!canUseDOM(如果在worker线程中,那么是不能操作DOM的),但是因为其只用于React的内部,同时有点hack的味道,无法用于其他的模块,所以后来被废弃掉了。虽然很多包和组件都使用React私有的ExecutionEnvironment库去检测一些特性,特别是服务端渲染。例如:
canUseDOM = require('react/lib/ExecutionEnvironment').canUseDOM; // BAD

但是使用这种React内部方法的方式并非最佳实践,因为在未来很可能被废弃掉

问题2:其内部是如何检测我们需要的特性的,如canUseDOM等

/*!
  Copyright (c) 2015 Jed Watson.
  Based on code that is Copyright 2013-2015,Facebook,Inc.
  All rights reserved.
*/
/* global define */

(function () {
	'use strict';

	var canUseDOM = !!(
		typeof window !== 'undefined' &&
		window.document &&
		window.document.createElement //window,window.document,window.document.createElement同时存在
	);

	var ExecutionEnvironment = {
		canUseDOM: canUseDOM,canUseWorkers: typeof Worker !== 'undefined',//在检测浏览器的webworker使用就是采用这种方式

		canUseEventListeners:
			canUseDOM && !!(window.addEventListener || window.attachEvent),canUseViewport: canUseDOM && !!window.screen //判断window.screen是否存在

	};

	if (typeof define === 'function' && typeof define.amd === 'object' && define.amd) {
		define(function () {
			return ExecutionEnvironment;
		});
	} else if (typeof module !== 'undefined' && module.exports) {
		module.exports = ExecutionEnvironment;
	} else {
		window.ExecutionEnvironment = ExecutionEnvironment;
	}

}());

上面的代码应该很容易看懂,此处不做分析

参考资料:

React的exenv模块

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读