我是新来的,所以请宽恕我。
我还阅读了这方面的所有线程,特别是React / JSX动态组件名称和React/JSX动态组件名称。解决办法没有奏效。
我使用的是选项卡样式的界面,用户选择一个选项卡,并加载适当的内容。父组件存储选项卡的内容状态,将相应的道具传递给内容子组件。然后,这个子组件加载正确的内容组件(作为自己的子组件)。
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循环通过道具,直到找到真正的道具。然后返回该键(例如“概述”)并创建一个变量(例如Component='TabbledContentOverview')。
但是,我的代码返回一个HTML <tabbedcontentoverview></tabbedcontentoverview>
问题
如何让React返回React组件而不是HTML标记?我似乎在使用正确的大写命名约定。我看过Facebook的文档。我只是不明白。
发布于 2018-01-12 12:20:19
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
};发布于 2015-08-12 22:27:58
您需要有一个对实际类的引用,以便从它创建一个元素(在JS或JSX中)。
持有一个键映射以响应类(即tabbedChildren),只需使用JS创建该元素:
var childComponent = tabbedChildren[key]
return React.createElement(childComponent)发布于 2015-08-12 23:39:22
首先,如果您在应用程序中使用引导程序,我建议您使用响应-引导选项卡。如果不是,我建议您至少看看他们的TabPane和TabbedArea的实现。
下面是你的应用程序中的一个例子:
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);
}
}
}
}https://stackoverflow.com/questions/31974552
复制相似问题