如何写出antd 那样的的组件化的ui?

最近有这样的一个需求,看了下antd的源码感觉有点复杂。。。有没有相对简单的类似项目,或者简单的demo让我先入个门??

阅读 3.1k
1 个回答

给你看下我自己封装的 bootstrapCol 组件吧,仅供参考,还有待完善,代码如下:

// 基于 bootstrap & react 封装的 Col Component

import React, { PropTypes } from 'react'

const Col = (props) => {
    let { xs, sm, md, lg, span, className } = props;
    if (!(xs || sm || md || lg)) {
        xs = 12;
    }
    if (span) {
        xs = sm = md = lg = span;
    }
    const colClass = [];
    className && colClass.push(className);

    const colKey = ['xs', 'sm', 'md', 'lg'];
    [ xs, sm, md, lg ].forEach((item, idx) => (item && colClass.push(`col-${colKey[idx]}-${item}`)));

    return (
        <div className={colClass.join(' ')}>
            { props.children }
        </div>
    )
}
Col.propTypes = {
    xs: PropTypes.number,
    sm: PropTypes.number,
    md: PropTypes.number,
    lg: PropTypes.number,
    className: PropTypes.string,
}

export default Col

然后在自己的封装目录下的 index.js 文件中,调用 Col 组件并导出即可:

import React, { Component, PropTypes } from 'react'
import './css/bootstrap.min.css'

// import others....
import Col from './Col'

export { Container, ContainerFluid, Row, Col }

目录结构

如此,你就可以在你的项目中其他任何地方,调用你自己写的诸如 Col 这样的组件了。好处就是:后续假如你又想用比如 antd 这样的库或框架时,你就直接修改 index.js 对应的组件就可以了,而不用到项目中的每个具体细节处一一修改,提升了后期的可维护性。

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题