1. 程式人生 > >基於React的Tab組件

基於React的Tab組件

names clas spa ren tle header() 調用 組件 cti

基於React的Tab組件

Tabs

renderHeader = () => {
    return React.Children.map( this.props.children , (element,index) => {
      const activeStyle = element.key === this.state.activeKey ? "activeTitle" : null;
      return (
          <span
              onClick={() => {
                this.setState({
                  activeKey: element.key
                })
              }}
              className={classnames("title", activeStyle)}
          >
            {element.props.title}
          </span>
      )
    })
  }

  renderContent = () => {
    return React.Children.map( this.props.children , (element,index) => {
      if (element.key === this.state.activeKey) {
        return (<div>{element.props.children}</div>)
      }
    })
  }

  render() {
    return (
        <div className="container">
          <div className="titleContainer">{this.renderHeader()}</div>
          <div className="contentContainer">{this.renderContent()}</div>
        </div>
    )
  }

TabPane

render() {
    return (
        <div>
          <div>{this.props.title}</div>
          <div>{this.props.children}</div>
        </div>
    )
  }

調用

render() {
    return (
        <div>
          <Tabs activeKey="1">
            <TabPane title="title1" key="1">content1</TabPane>
            <TabPane title="title2" key="2">content2</TabPane>
          </Tabs>
        </div>
    )
  }

基於React的Tab組件