反应动态组件命名

时间:2015-08-12 20:14:59

标签: javascript reactjs react-jsx

我是React的新手所以请怜悯。

我还阅读了其中的所有主题,特别是React / JSX Dynamic Component NameReact/JSX dynamic component names。解决方案不起作用。

我使用标签式界面,用户选择标签并加载相应的内容。父组件存储选项卡的内容状态,将相应的道具传递给内容子项。然后这个孩子加载正确的内容组件(作为自己的孩子)。

var TabbedContent = React.createClass({

loadMenu: function() {
    var menus=this.props.carDivState.vehicleDetailState;
    for (key in menus) {
        if (menus.hasOwnProperty(key)) {
            if (menus[key]) { 
                var Component='TabbedContent'+key;
                return <Component />;
            }         
        }
    }
},

render: function() {
    return (
        <div className="TabbedContent">
            <div className="contentWrapper">
                {this.loadMenu()}
            </div>
        </div>
    )
}

});

loadMenu遍历道具,直到找到真正的道具。然后它返回该密钥(例如&#34;概述&#34;)并创建一个变量(例如,Component =&#39; TabbledContentOverview&#39;)。

但是,我的代码会返回HTML代码<tabbedcontentoverview></tabbedcontentoverview>

问题

如何让React返回React组件而不是HTML标签?我似乎正在使用正确的大写命名约定。我已经阅读了Facebook文档。我只是不明白。

3 个答案:

答案 0 :(得分:1)

您需要引用一个实际的类才能从中创建一个元素(在JS或JSX中)。

保存React类的键映射(即65.85%),然后使用JS API创建此元素:

tabbedChildren

https://facebook.github.io/react/docs/top-level-api.html

答案 1 :(得分:1)

首先,如果您正在为您的应用使用Bootstrap,我建议您使用react-bootstrap`s tab。如果您不是,我建议您至少查看他们TabPaneTabbedArea的实施情况。

以下是您的应用中的示例:

const tabbedAreaInstance = (
  <TabbedArea defaultActiveKey={2}>
    <TabPane eventKey={1} tab='Tab 1'>TabPane 1 content</TabPane>
    <TabPane eventKey={2} tab='Tab 2'>TabPane 2 content</TabPane>
    <TabPane eventKey={3} tab='Tab 3' disabled>TabPane 3 content</TabPane>
  </TabbedArea>
);

React.render(tabbedAreaInstance, mountNode);

现在,回到您的问题,如果您想按名称创建组件,只需从React.createElement内调用loadMenu

loadMenu: function() {
    var menus=this.props.carDivState.vehicleDetailState;
    for (key in menus) {
        if (menus.hasOwnProperty(key)) {
            if (menus[key]) { 
                return React.createElement('TabbedContent'+key);
            }         
        }
    }
}

答案 2 :(得分:1)

https://github.com/vasanthk/react-bits/blob/master/patterns/30.component-switch.md

import HomePage from './HomePage.jsx';
import AboutPage from './AboutPage.jsx';
import UserPage from './UserPage.jsx';
import FourOhFourPage from './FourOhFourPage.jsx';

const PAGES = {
  home: HomePage,
  about: AboutPage,
  user: UserPage
};

const Page = (props) => {
  const Handler = PAGES[props.page] || FourOhFourPage;

  return <Handler {...props} />
};

// The keys of the PAGES object can be used in the prop types to catch dev-time errors.
Page.propTypes = {
  page: PropTypes.oneOf(Object.keys(PAGES)).isRequired
};
相关问题