• 组件切换
    • 参考资料:

    组件切换

    一个可切换的组件实际上是包含了多个组件, 选择渲染其中某个组件的组件.
    我们使用对象来将props的值和组件做上映射.

    1. import HomePage from './HomePage.jsx';
    2. import AboutPage from './AboutPage.jsx';
    3. import UserPage from './UserPage.jsx';
    4. import FourOhFourPage from './FourOhFourPage.jsx';
    5. const PAGES = {
    6. home: HomePage,
    7. about: AboutPage,
    8. user: UserPage
    9. };
    10. const Page = (props) => {
    11. const Handler = PAGES[props.page] || FourOhFourPage;
    12. return <Handler {...props} />
    13. };
    14. // The keys of the PAGES object can be used in the prop types to catch dev-time errors.
    15. Page.propTypes = {
    16. page: PropTypes.oneOf(Object.keys(PAGES)).isRequired
    17. };

    参考资料:

    • https://hackernoon.com/10-react-mini-patterns-c1da92f068c5