react简单的tab切换 (styled-components)

其实,在我们日常的编程当中,经常会碰到tab切换的模块,那么,实现他的方法也有很多中,下面是一款简单,容易理解的react tab切换方法。

 通过设置state中的current 属性去控制tab 和 内容模块。

this.state = {
      current: 0,
      cities:['香港','北京','上海','台北'],
      content:[{
        number: '13866666666',
        email: '[email protected],
        time: 'test123',
      },{
        number: '13877777777',
        email: '[email protected]',
        time: 'test456',
      },{
        number: '13888888888',
        email: '[email protected]',
        time: 'test789',
      },{
        number: '13899999999',
        email: '[email protected]',
        time: 'test000',
      }]
    };

定义一个tab onClick 事件的方法 itemNav,并接收当前点击的index索引号,赋值给current

itemNav = (index) =>{
   this.setState({
     current: index,
   })
}

循环出tab 标签  并添加点击改变index索引事件,添加onClick执行itemNav方法,传入当前点击的索引号

<TabContent>
    {this.state.cities.map((item,index) =>{
         return (
            <span key={index} className={ index === this.state.current ? 'state-active' : ''} onClick={ () => { this.itemNav(index)} }>{item}</span>
         );
     })}
</TabContent>

循环出内容模块,通过index索引号改变需要显示模块

<ContentContainer>
    {this.state.content.map((item,index) =>{
            return (
              <ul key={index} className={index === this.state.current ? 'state-active' : ''} >
                <li>
                  <p>测试标题</p>
                </li>
                <li>
                  <p>
                    <TelPhone fontSize="14px" color="#687593" />
                    <span>{item.number}</span>
                  </p>
                </li>
                <li>
                  <p>
                    <Email fontSize="14px" color="#687593" />
                    <a href={`mailto:${item.email}`}>{item.email}</a>
                  </p>
                </li>
                <li>
                  <p><span>{item.time}</span></p>
                </li>
              </ul>
            );
          })}
</ContentContainer>

  

 这样,一个简单的react tab 切换就搞定了... css样式需要您添加自己需要的样式...(不喜勿喷,希望这个简单的tab切换能帮助到您)

猜你喜欢

转载自www.cnblogs.com/a-cat/p/9449162.html