JS:反应和全局命名空间污染 [英] JS: React and global namespace pollution

查看:66
本文介绍了JS:反应和全局命名空间污染的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在考虑在新网站中使用react,我仍然想知道如何使用react组件处理全局命名空间。例如,如果我像这样定义几个React组件:

I'm considering to use react in a new website and I'm still wondering, how to handle the global namespace with react components. For example, if I define several React Components like this:

var MySlider = React.createClass({ // snip });
var MyAlert = React.createClass({ // snip });
var MyDropdown = React.createClass({ // snip });

渲染组件如下所示:

React.renderComponent(
    <MySlider />,
    document.getElementById('content')
);

但是,我更喜欢命名我的组件以避免污染全局命名空间。

However, I'd prefer to namespace my components to avoid polluting the global namespace.

var Namespace = {};
Namespace.MySlider = React.createClass({ // snip });

在渲染方面,由于命名空间,我找不到组件。

When it comes to rendering, the component is not found due to namespacing, I guess.

React.renderComponent(
    <Namespace.MySlider />, // component is not found
    document.getElementById('content')
);

我在这里缺少什么?只是忽略全局名称空间污染或者有没有可能命名你的组件?

What am I missing here? Just ignore global namespace pollution? Or is there a possibility to namespace your components?

谢谢!

推荐答案

<这不是一个React JS问题,因为任何大型JavaScript代码库都必须处理模块加载。我建议在JavaScript中使用命名空间开始接近它,而不是使用模块加载器。

This is not exactly a React JS question since any large JavaScript codebase has to deal with module loading. I suggest forgoing namespacing in JavaScript the way you started to approach it and instead use a module loader.

你会对此有很多意见,但请看一些广泛的 - 使用的模块加载器:

You will get many opinions on this, but look at some of the widely-used module loaders:

  • Browserify
  • rollup.js
  • Webpack

这篇关于JS:反应和全局命名空间污染的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆