使用react實(shí)現(xiàn)一個(gè)tab組件的方法:1、通過“export default props => {…}”方式創(chuàng)建TAB button組件;2、通過“tab-group-layout.js”組件來傳“tabIndex”,并設(shè)置默認(rèn)選中的tab效果;3、用react繼承“react.component”組件里的onMouseOver和OnMouseOut方法即可。
前端(vue)入門到精通課程:進(jìn)入學(xué)習(xí)
Apipost = Postman + Swagger + Mock + Jmeter 超好用的API調(diào)試工具:點(diǎn)擊使用
本教程操作環(huán)境:windows7系統(tǒng)、react18.0.0版、Dell G3電腦。
怎么使用react實(shí)現(xiàn)一個(gè)tab組件?
react寫Tab組件
使用react寫TAB欄組件和對應(yīng)hover事件(背景:在用gatsby開發(fā)頁面時(shí),遇到這樣的組件效果,順便記錄一下)
1、效果
默認(rèn)選中的tab選中效果 和 鼠標(biāo)放上去的hover效果
當(dāng)鼠標(biāo)滑過右側(cè)的tab時(shí),也會有和第一個(gè)一樣的選中效果!
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')}>產(chǎn)品介紹</ListLink> <ListLink to="/about/" selected={(tabIndex==='about')}>成功案列</ListLink> <ListLink to="/contact/" selected={(tabIndex==='contact')}>服務(wù)支持</ListLink> <ListLink to="/sweet-pandas-eating-sweets/" selected={(tabIndex==='sweet-pandas-eating-sweets')}>資源中心</ListLink> </ul> </div> ) }
使用這個(gè)組件傳過來 tabIndex 設(shè)置默認(rèn)選中的tab效果;也可以自己處理展示的邏輯
4、對應(yīng)的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、當(dāng)前組件的hover使用的是css樣式控制,也可以用 react繼承 react.component組件里的onMouseOver和OnMouseOut方法來實(shí)現(xiàn)
推薦學(xué)習(xí):《react視頻教程》