react的Tab栏案例

大家好,我是梅巴哥er ,这里介绍Tab栏案例:

用到的react知识点:

  • 构造组件
  • 点击事件
  • 点击事件传参
  • 状态改变

先来看下效果:

在这里插入图片描述
用到的三块代码:
1,index.js的代码:

import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App1 from './App1';


ReactDOM.render(
    <App1 />,
    document.getElementById('root')
)

2,App1.js 的代码:

import React, {Component} from 'react'
import './App1.css'
class App1 extends Component {
    constructor(props) {
        super(props)
        // 设置初始状态,num为1,就是第一个按钮和内容显示
        this.state = {
            num: 1
        }
    }
    // 核心步骤: 给点击事件设置参数,也就是说,
    // 如果你点击了1,number就是1,状态的num就变成1,那么1的内容就显示
    // 同理,点击2和3也有同样的变化效果
    handleClick = (number) => {
        this.setState({
            num: number
        })
    }
    render() {
        return (
            <div className="tab_con">
                <div className="tab_btns">
                    <input type="button" 
                    {/* 这里需要加个判断,如果状态变成了1,就把类名给1,
                    让1显示。如果状态的num不是1,那就让类名为空,不显示*/}
                    className={ this.state.num == 1 ? 'active' : '' } 
                    value="按钮1" 
                    {/* 点击事件传参,把参数1通过形参number 传给setState的num 
                    让被点击的按钮状态发生对应的变化*/}
                    onClick={ () => {this.handleClick(1) }} />
                    <input type="button" 
                    className={ this.state.num == 2 ? 'active' : '' }
                    value="按钮2"
                    onClick={ () => { this.handleClick(2) }} />
                    <input type="button" 
                    className={ this.state.num == 3 ? 'active' : '' }
                    value="按钮3"
                    onClick={ () => { this.handleClick(3) }} />
                </div>
                <div className="tab_cons">
                    <div className={ this.state.num == 1 ? 'current' : '' }>内容1</div>
                    <div className={ this.state.num == 2 ? 'current' : '' }>内容2</div>
                    <div className={ this.state.num == 3 ? 'current' : '' }>内容3</div>
                </div>
            </div>
        )
    }
}

export default App1

3,App1.css 的代码:

* {
    margin: 0;
    padding: 0;
}
.tab_con {
    width: 144px;
    height: 122px;
    margin-top: 100px;
    margin-left: 100px;
}
.tab_btns input {
    outline: 0;
    border: 1px solid #f4f4f4;
}
.active {
    background-color: pink;
}
.tab_cons {
    width: 112px;
    height: 80px;
    background-color: pink;
}
.tab_cons div {
    display: none;
}
.tab_cons .current {
    display: block;
}

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值