react实现tab切换

1.方法一




    
    
    
    
    
    
    
    


    

2.利用脚手架+父传子

1.App.jsx

import React, { Component } from 'react'
import Tabcontroll from './Tabcontroll'
export default class App extends Component {
    state={
        titles:['java','js','vue','react']
    }
render() {
    return (
        
) } }

2.Tabcontroll.jsx

import React, { Component } from 'react'
import './app.css'
export default class Tabcontroll extends Component {
    constructor(props){
        super(props);
        this.state={
            curentIndex:0
        }
    }
    getItem(index){
        this.setState({
            curentIndex:index
        })
    }
render() {
    const{curentIndex}=this.state
    return (
        
    { this.props.titles.map((item,index)=>
  • {this.getItem(index)}}>{item}
  • )}
{ this.props.titles.map((item,index)=>

{item}

) }
) } }

3.app.css

.parent{
    display: flex;
    height: 50px;
    width: 100%;
    background-color: gainsboro;
}
li{
    flex: 1;
    list-style: none;
    display: block;
    line-height: 50px;    
}
p{
    display: none;
}
.active{
    color: red;
    text-decoration: underline red;
}
.display{
    display: block;
}

3.脚手架+父子通信

parent.jsx

import React, { Component } from 'react'
import Child from './Child'

export class Parent extends Component {
    state = {
        titles:['java','js','vue','react'],
        i:0
    }
    // 父传子 获取索引
    tabClick(index){
        this.setState({
            i:index
        })
    }
render() {
    const{titles,i} = this.state;
    return (
        
{/* 父传子 */}

{titles[i]}

) } } export default Parent

child.jsx

import React, { Component } from 'react'
import './style.css'
export class Child extends Component {
    state={
        tabIndex:0
    }
    getIndex=(index)=>{
        this.setState(
            {
                tabIndex:index
            }
        )
        // 子传父
        this.props.tabClick(index)
    }
render() {
    const {tabIndex} = this.state
    return (
        
{this.props.titles.map((item,index)=>{ return(
this.getIndex(index)}>{item}
) })}
) } } export default Child

style.css

.content{
    display: flex;
    height: 40px;
    background-color: gainsboro;
    align-items: center;
}
.content .item{
    flex:1
}
.active{
    color: red;
}

你可能感兴趣的:(#React,react.js,javascript,前端)