React API implementation in the React API. When I saw react. Children, I thought it was great, so I used it manually to implement a simple Tabs component.

  1. Entry file usetab.jsx
import React from 'react'
import {Tabs, TabPlane} from '.. /myTab'

const UseTab = () = > {
  return <>
    <Tabs activeIndex={1} onChange={(e)= > {console.log(e,'ee')}}>
      <TabPlane key={1} name="tab1">The contents of TAB 1</TabPlane>
      <TabPlane key={2} name="tab2">Contents of TAB 2</TabPlane>
      <TabPlane key={3} name="tab3">TAB 3 content</TabPlane>
    </Tabs>
  </>
}

export default UseTab
Copy the code
  1. Custom internal component Tabs
import React, { useEffect, useState } from 'react'

import './index.css'
/** * Toggle tabs * 1. Use the react. chilren method * 2. Test if you can use the simple array map method */
const TabPlane = ({children}) = > {
  return <div>
    {children}
  </div>
}

const Tabs = ({children, activeIndex, onChange}) = > {
  const [currentIndex, setCurrentIndex] = useState(1)
  useEffect(() = > {
    if (activeIndex) {
      setCurrentIndex(activeIndex)
    }
  }, [activeIndex])

  const tabClick = (key) = > {
    if (key === currentIndex) {
      return
    }
    setCurrentIndex(key)

    onChange(key)
  }

  return <div className="card">
    <div className="topclick">
      {React.Children.map(children, (element, index)=>{
        console.log(element, 'element')
        const { name } = element.props
        return <div style={{color: currentIndex= =element.key ? '#7893f7' :"'}}onClick={()= > tabClick(element.key)}>{name}</div>
      })}
    </div>
    <div className="tabContainer">
      {React.Children.map(children, (element, index)=>{
        const { children } = element.props
        return <div className={currentIndex= =element.key ? 'block' : 'none'} >{children}</div>
      })}
    </div>
  </div>
}

export { Tabs, TabPlane }
Copy the code
  1. style.css
.card{
 background-color: #f6f6f6;
 font-size: 12px;
 color: # 000;
 width: 400px;
 height: 200px;
 border-radius: 4px;
 border: 2px solid #ececee;
 display: flex;
 flex-direction: column;
 justify-content: center;
 align-items: flex-start;
}
.topclick{
 display: flex;
 justify-content: flex-start;
 align-items: center;
 border-bottom: 1px solid #ececee;
}
.topclick > div{
 width: 80px;
 height: 30px;
 line-height: 30px;
 text-align: center;
 cursor: pointer;
}
.tabContainer{
 flex-grow: 1;
}

.block{
 display: block;
 padding: 10px 20px;
}
.none{
 display: none;
}
Copy the code