大家好,我是梅巴哥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;
}