使用React+styled-components实现标签页底部下划线及选中高亮效果
实现方案
你需要分别修改样式文件和业务逻辑代码,具体修改如下:
1. 样式文件(messageTab.elements.js)修改
修改后的完整样式代码:
import styled from 'styled-components'; const ListItems = styled.li` margin-right : 6%; /* 动态控制激活状态文字颜色 */ color: ${props => props.isActive ? '#2D7FF9' : '#9095A4'}; position: relative; cursor: pointer; padding: 8px 0; /* 加过渡动画让切换更顺滑 */ transition: all 0.2s ease; /* 用伪元素实现底部指示条 */ &::after { content: ''; position: absolute; bottom: 0; left: 0; width: 100%; height: 2px; background-color: #2D7FF9; /* 只有激活状态才显示指示条 */ display: ${props => props.isActive ? 'block' : 'none'}; } `; const List = styled.ul` display : flex; list-style-type : none; float : right; flex-direction: row; /* 整个标签栏加底部灰色基线 */ border-bottom: 1px solid #E5E7EB; width: 100%; margin: 0; padding: 0; `; const Div = styled.div` display : flex; margin-left : 6%; width: 100%; `; export { List, ListItems, Div };
2. 业务逻辑代码修改
修改后的完整业务代码:
// 补上缺失的React和useState导入,避免运行报错 import React, { useState } from 'react'; import { List, ListItems, Div } from './messageTab.elements'; function MessageTab() { return ( <Tabs> <div label="Recent"> Recent component </div> <div label="Unread"> Unread component </div> <div label="Groups"> Groups component </div> </Tabs> ) } function Tabs(props) { const [activeTab, setActiveTab] = useState(props.children[0].props.label) const switchTabs = (tab) => { setActiveTab(tab); } return ( <Div> <List> {props.children.map((child) => { const { label } = child.props; return ( <Tab activeTab={activeTab} key={label} label={label} onClick={switchTabs} /> ); })} </List> </Div> ); } function Tab(props) { const { label, onClick, activeTab } = props; return ( <ListItems // 传递激活状态参数给样式组件 isActive={activeTab === label} onClick={() => onClick(label)} > {label} </ListItems> ); }
可调整项说明
如果需要修改指示条的颜色、粗细、圆角,直接调整ListItems的&::after伪元素对应的样式属性即可;如果要修改激活状态的文字颜色,修改ListItems的color属性对应的激活色值即可。
内容的提问来源于stack exchange,提问作者championq45
相关产品推荐
相关产品推荐

