什么是更简洁的写作方式. pageType始终与React元素名称相同,我应该可以取消switch语句. import React, {Component, PropTypes} from 'react';import Standard from './Standard/Standard';import Banners from './Banners/Banne
import React, {Component, PropTypes} from 'react'; import Standard from './Standard/Standard'; import Banners from './Banners/Banners'; export default class ProductPages extends Component { static propTypes = { pageType: PropTypes.string.isRequired } render() { let ProductPage; switch (this.props.pageType) { case 'Standard': ProductPage = <Standard products={products}/>; break; case 'Banners': ProductPage = <Banners products={products}/>; break; default: throw new Error('pageType is not valid'); } return ProductPage; } }由于标准和横幅是React组件而不仅仅是简单的元素,你需要做这样的事情,
const Components = { Standard, Banners }; class ProductPages extends React.Component { render() { const ProductPage = Components[this.props.pageType]; return <ProductPage products={ [] } /> } }
Example
或者使用React.createElement
const Components = { Standard, Banners }; class ProductPages extends React.Component { render() { return React.createElement(Components[this.props.pageType], { products: [] }) } }
Example
但是,正如您在这里可以看到保存对Components的引用然后使用它的主要想法.您可以在React GitHub issues上阅读有关此案例的更多信息
注意
const Components = { Standard, Banners };
是新的ECMAScript 6功能,称为Object Literal Property Value Shorthand