0
点赞
收藏
分享

微信扫一扫

React 小案例 无线首页底部导航组件

南柯Taylor 2023-01-03 阅读 71


效果:底部页面导航 点击当前图标 图标高亮

页面结构

1.将所用到的小图标文件放置在static文件夹下

2.在src下新建tabbar文件夹,用于存放组件资源

3.页面代码

注意:

将本页面的css引入,

定义tarbarArr数组,用于循环小图标和文字,

遍历数组tarbarArr:

{
tarbarArr.map((v,i)=>(

))
}复制代码

用div遍历展示小图标:

<div className={"iconfont "+v.img}/>复制代码

给每个按钮添加点击事件:

用箭头函数将当前index传递出去,为触发后面的点击当前高亮

onClick={()=>this.itemChange(i)复制代码

在state中定义默认高亮选中为第一个按钮:

constructor(props){
super(props)
this.state={
index:0
}
}复制代码

点击事件函数:

将i作为函数参数传递出去,点击每个按钮,即修改state中的index为i(当前)

itemChange = (i)=>{
this.setState({
index:i
})
}复制代码

给按钮再添加一个active类,即如果state中的index为当前i,即添加active,如果不是,即添加空(不添加)

className={"tabbar-item"+(this.state.index===i?' active':'')复制代码

index.js文件里所有内容:

import React,{Component} from 'react'
import './index.css'
const tarbarArr =[
{
img:'icon-home',
text:'首页'
},
{
img:'icon-fenlei',
text:'分类'
},
{
img:'icon-gouwuchekong',
text:'购物车'
},
{
img:'icon-yonghu',
text:'我的'
}
]
class Tabbar extends Component{
constructor(props){
super(props)
this.state={
index:0
}
}
itemChange = (i)=>{
this.setState({
index:i
})
}
render(){
return(
<div className="tabbar">
<div className="tabbar-content">
{
tarbarArr.map((v,i)=>(
<div key={i} className={"tabbar-item"+(this.state.index===i?' active':'')} onClick={()=>this.itemChange(i)}>
<div className={"iconfont "+v.img}/>
<div>{v.text}</div>
</div>
))
}
</div>
</div>
);
}
}

export default Tabbar;复制代码

css中全部内容:

.tabbar{
height: 50px;
position: absolute;
bottom: 0;
width: 100%;
border-top: 1px solid #ccc;
padding: 5px 0;
}
.tabbar-content{
display: flex;
}
.tabbar-item{
flex: 1;
}
.tabbar-item .iconfont{
font-size: 28px;
}

//点击当前变色
.active{
color: #ff4e41;
}复制代码

在App.js中引入:

引入Tabbar组件,和小图标,

将Tabbar标签放置,

 

import Tabbar from './components/tabbar'
import './components/static/iconfont.css'复制代码

render() {
return (
<div className="App">
<Tabbar/>
</div>
);
}

 

举报

相关推荐

0 条评论