React.js:是否可以在使用JSX引用它们的同时命名子组件? [英] React.js: Is it possible to namespace child components while still using JSX to refer to them?

查看:94
本文介绍了React.js:是否可以在使用JSX引用它们的同时命名子组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以假设我有一个名为 ImageGrid 的组件,它定义如下:

So let's say I have a component called ImageGrid and it is defined as below:

window.ImageGrid = React.createClass({
    render: function() {
        return (
            <div className="image-grid">
                <ImageGridItem />
            </div>
        );
    }
});

如你所见,它包含一个名为 ImageGridItem 。其定义如下。

As you can see it includes a child react component called ImageGridItem. Which is defined below.

window.ImageGridItem = React.createClass({
    render: function() {
        return (
            <div className="item-container">something</div>
        );
    }
});

只要两者都是窗口的直接属性。但这有点可怕,所以我想在 window.myComponents 的命名空间下将所有反应组件分组。

This works fine as long as both are directly properties of window. But this is kind of horrible so I'd like to group up all my react components under a namespace of window.myComponents for example.

所以定义改为:

window.myComponents.ImageGrid     = React.createClass({...});
window.myComponents.ImageGridItem = React.createClass({...});

现在的问题是, ImageGrid 是指到< ImageGridItem /> 在它的render()函数中,它的JS版本被编译为JS为 ImageGridItem()当然这是未定义的,因为它现在实际上是 myComponents.ImageGridItem()并且反应抱怨它无法找到它。

The problem now is that as ImageGrid refers to <ImageGridItem /> in it's render() function, the JS version of this gets compiled out to JS as ImageGridItem() which of course is undefined since it's now actually myComponents.ImageGridItem() and react complains it can't find it.

是的我知道我不能为那个组件编写JSX并手动执行 myComponents.ImageGridItem({attr:'val'})但是我d真的更喜欢使用JSX html语法快捷方式,因为它更容易阅读和开发。

Yes I realise I can just not write JSX for that component include and manually do myComponents.ImageGridItem({attr: 'val'}) but I'd really prefer to use the JSX html syntax shortcut as it's much easier to read and develop with.

是否有任何方法可以让这个工作仍在使用< ImageGridItem /> 语法?如果没有,是否可以在JSX中定义JS命名空间?

Are there any ways to get this to work while still using the <ImageGridItem /> syntax for children? And if not is it possible to define the JS namespace within the JSX?

推荐答案

此拉取请求刚刚合并:

https://github.com/facebook/react / pull / 760

它允许您编写类似< myComponents.ImageGridItem /> 在React 0.11和更新版本中。

It allows you to write things like <myComponents.ImageGridItem /> in React 0.11 and newer.

也就是说,建议使用正确的模块系统来管理依赖项,以避免引入不需要的代码。

That said, a proper module system is the recommended way to manage dependencies to avoid pulling in code that you don't need.

这篇关于React.js:是否可以在使用JSX引用它们的同时命名子组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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