React.js: Is it possible to namespace child components while still using JSX to refer to them?

隐身守侯 提交于 2019-12-12 08:01:54

问题


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>
        );
    }
});

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>
        );
    }
});

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.

So the definitions change to:

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

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.

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.

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?


回答1:


This pull request was just merged:

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

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.




回答2:


Currently, there isn't a way to do this. Namespacing with JSX is on the todo list.

Most people use some kind of module system (browserify, webpack, requirejs), which replace namespacing and allow components to be used easily. There are a lot of other benefits, so I very much recommend looking into it.



来源:https://stackoverflow.com/questions/23653616/react-js-is-it-possible-to-namespace-child-components-while-still-using-jsx-to

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!