Semantic-UI的React实现(三):基本元素组件

Semantic-UI官方的React组件化已经快要接近完成了,最近开放了官网:http://react.semantic-ui.com/。从官网看,基本组件已经基本完备,还有几个Addon也在进行中。react

基本元素组件

Semantic-UI中的基本元素均为纯CSS类定义的组件,没有js的操做,所以实现起来比较简单。有了前面基础类UiElement和辅助类PropsHelper的实现,要实现一个基本元素组件很是轻松。组件化

以Button组件举例。Button组件能够单独存在,也能够做为组组件使用。另外Button组件也容许简单的Animation存在,即一对显示/隐藏的组件能够随鼠标状态而切换。外部调用的大体形式为:ui

<Button.Group size='small'>
    <Button primary onClick={this.handleClickBtn1}>按键1</Button>
    <Button color='blue' onClick={this.handleClickBtn2}>按键2</Button>
    <Button animated  onClick={this.handleClickBtn3}>
        <Button.Content visible>按键3显示内容</Button>
        <Button.Content hidden>按键3隐藏内容</Button>
    </Button>
</Button.Group>

调用方式其实是很直观的,属性均做为props传入到Button组件中,事件系统的回调方法也与普通方式并没有二致。相对复杂的处理,是要整理全部组件的共通属性,定义它们的类型和取值范围。this

Button

Button做为基本组件,有很是多经常使用的属性。这些属性在命名上,基本参照Semantic-UI的原有CSS类名,在Button.js中用常量PROP_TYPES来定义。code

const PROP_TYPES = [
  'primary', 'secondary', 'animated', 'labeled', 'basic', 'inverted', 'color',
  'size', 'fluid', 'active', 'disabled', 'loading', 'compact', 'circular', 'positive',
  'negative', 'floated', 'attached', 'iconed', 'dropdown'
];

组件根据PropsHelper的相关方法来生成propTypes定义,而且经过父类(UiElement)的createElementStyle方法来编辑和组装所使用的CSS类。另外,还经过父类的getEventCallback方法,来声明相关的事件系统回调处理。继承

class Button extends UiElement {
  
  // 类型定义
  static propTypes = {
    ...PropsHelper.createPropTypes(PROP_TYPES)
  };
  
  render() {
  
    // 生成元素style
    let style = this.createElementStyle(this.props, PROP_TYPES, 'button');
    
    return (
      <div id={this.props.id} className={style} {...this.getEventCallback()} tabIndex='0'>
        {this.props.children}
      </div>
    );
  }
}

Button.Group

与Button组件相似,Group组件也继承于UiElement以生成其声明的公有属性对应的CSS类。事件

// 属性定义
const GROUP_PROP_TYPES = [
  'iconed', 'vertical', 'labeled', 'equalWidth', 'color',
];

/**
 * 按键组组件
 */
class Group extends UiElement {

  // 类型定义
  static propTypes = {
    ...PropsHelper.createPropTypes(GROUP_PROP_TYPES)
  };

  /**
   * 取得渲染内容
   */
  render() {

    // 生成元素Style
    let style = this.createElementStyle(this.props, PROP_TYPES, 'buttons');

    return (
      <div id={this.props.id} className={style} {...this.getEventCallback()}>
        {this.props.children}
      </div>
    );
  }
}

Button.Content

Content组件的实现更简单,直接贴代码。ci

class Content extends React.Component {

  static propTypes = {
    visible: React.PropTypes.bool
  };

  render() {
    return (
      <div className={this.props.visible ? 'visible content' : 'hidden content'}>
        {this.props.children}
      </div>
    )
  }
}

其余组件

经过以上示例能够看出,有了UiElement和PropsHelper类的处理,基本元素组件的实现是很是简单的。只需声明组件所使用的属性,并使用父类方法编辑和组装CSS类便可。其余组件如Label,Icon,Image,Grid等,均沿同一思路封装便可完成。pdo

难点是什么?

在封装基本元素组件的过程当中,我感受难点在于:get

  1. 封装和抽象元素的共通处理(目前已基本成型)

  2. 管理众多组件的共通属性(目前还在摸索中)

看过官方相关处理的源码,感受思路仍是大致一致的,这点让我感受多了一些自信(๑•̀ㅂ•́)و✧

相关文章
相关标签/搜索