使用react实现一个tab组件的方法:1、通过“export default props => {...}”方式创建tab button组件;2、通过“tab-group-layout.js”组件来传“tabindex”,并设置默认选中的tab效果;3、用react继承“react.component”组件里的onmouseover和onmouseout方法即可。
本教程操作环境:windows7系统、react18.0.0版、dell g3电脑。
怎么使用react实现一个tab组件?
react写tab组件
使用react写tab栏组件和对应hover事件(背景:在用gatsby开发页面时,遇到这样的组件效果,顺便记录一下)
1、效果
默认选中的tab选中效果 和 鼠标放上去的hover效果
当鼠标滑过右侧的tab时,也会有和第一个一样的选中效果!
2、tab-button.js 组件
import react from "react"import { css } from "@emotion/core"import { link } from "gatsby"import jdystyles from "./container.module.css" // tab button 组件export default props => { return ( <li css={css`font-size: 18px;margin-left:18px;margin-right: 18px;display:flex;flex-direction: column;align-items:center;justify-content:center`} > <link css={css`font-size: 18px;padding: 20px 12px;`} classname={ (props.selected?jdystyles.header_hover_default:jdystyles.header_hover) } to={props.to}>{props.children}</link> </li> )}
3、tab-group-layout.js 组件
import react from "react"import { css } from "@emotion/core"import { link } from "gatsby"import listlink from "../components/tab-button"import registerbutton from "../components/round-button"export default ({ tabindex }) => { return ( <div> {/* tab */}<ul style={{ liststyle: `none`, float: `right` }} css={css`display: flex;justify-content: space-between;align-items: center;`}><listlink to="/official-site/" selected={(tabindex==='official-site')}>产品介绍</listlink><listlink to="/about/" selected={(tabindex==='about')}>成功案列</listlink><listlink to="/contact/" selected={(tabindex==='contact')}>服务支持</listlink><listlink to="/sweet-pandas-eating-sweets/" selected={(tabindex==='sweet-pandas-eating-sweets')}>资源中心</listlink></ul> </div> )}
使用这个组件传过来 tabindex 设置默认选中的tab效果;也可以自己处理展示的逻辑
4、对应的css样式 container.module.css
.header_hover{ color: #333;} .header_hover_default{ color: #0084ff!important; border-top: 3px solid #0084ff;} .header_hover:hover{ color: #0084ff!important; border-top: 3px solid #0084ff;}
5、当前组件的hover使用的是css样式控制,也可以用 react继承 react.component组件里的onmouseover和onmouseout方法来实现
推荐学习:《react视频教程》
以上就是怎么使用react实现一个tab组件的详细内容。