[英]How to switch css class for active tab of react-bootstrap?
我正在嘗試向活動選項卡添加自定義樣式,但不知道如何切換活動選項卡的樣式類。
以下是我的代碼:
import React, { useState } from "react";
import "./styles.css";
import { Container, Row, Col, Tab, Nav } from "react-bootstrap";
export default function App() {
const [key, setKey] = useState("first");
const ActiveStyle = {
textAlign: "center",
background: "white",
borderRadius: "2em",
padding: " 0.3em 1.5em",
letterSpacing: "0.2em"
};
const inActiveStyle = {
...ActiveStyle,
background: "transparent",
"border-color": "transparent",
color: "inherit"
};
return (
<div className="App">
<Container style={{ width: "auto" }}>
<Tab.Container activeKey={key} onSelect={key => setKey(key)}>
<Row style={{ padding: "1em 1em", background: "#EEEEEE" }}>
<Col>
<Nav.Link
eventKey="first"
style={key === "first" ? ActiveStyle : inActiveStyle}
>
<span style={{ fontSize: "larger" }}>Q&A </span>
</Nav.Link>
</Col>
<Col>
<Nav.Link
eventKey="second"
style={key === "second" ? ActiveStyle : inActiveStyle}
>
<span>Exams</span>
</Nav.Link>
</Col>
</Row>
<Tab.Content>
<Tab.Pane eventKey="first">
<Row style={{ height: "90vh" }}>
<p>TAB 1</p>
</Row>
</Tab.Pane>
<Tab.Pane eventKey="second">
<Row style={{ height: "90vh" }}>
<p>TAB 2</p>
</Row>
</Tab.Pane>
</Tab.Content>
</Tab.Container>
</Container>
</div>
);
}
您可以使用狀態來識別這樣的活動選項卡(您可以重構它以滿足您的需要)
推薦閱讀材料是受控/非受控組件https://reactjs.org/docs/forms.html#controlled-components
import React, { useState } from "react";
import "./styles.css";
import { Container, Row, Col, Tab, Nav } from "react-bootstrap";
export default function App() {
const [key, setKey] = useState('first');
const ActiveStyle = {
textAlign: "center",
background: "white",
borderRadius: "2em",
padding: " 0.3em 1.5em",
letterSpacing: "0.2em"
};
const inActiveStyle = {
...ActiveStyle,
background: 'transparent',
'border-color': 'transparent',
'color': 'inherit'
};
return (
<div className="App">
<Container style={{ width: "auto" }}>
<Tab.Container activeKey={key} onSelect={key => setKey(key)}>
<Row style={{ padding: "1em 1em", background: "#EEEEEE" }}>
<Col>
<Nav.Link
eventKey="first"
style={ key === 'first' ? ActiveStyle : inActiveStyle}
>
<span style={{ fontSize: "larger" }}>Q&A </span>
</Nav.Link>
</Col>
<Col>
<Nav.Link eventKey="second" style={ key === 'second' ? ActiveStyle : inActiveStyle}>
<span>
Exams
</span>
</Nav.Link>
</Col>
</Row>
<Tab.Content>
<Tab.Pane eventKey="first">
<Row style={{ height: "90vh" }}>
<p>TAB 1</p>
</Row>
</Tab.Pane>
<Tab.Pane eventKey="second">
<Row style={{ height: "90vh" }}>
<p>TAB 2</p>
</Row>
</Tab.Pane>
</Tab.Content>
</Tab.Container>
</Container>
</div>
);
}
如果您使用的是 bootstrap 或 react-bootstrap,您只需要在 css 文件中添加一個 css 指令。 例如:
a.nav-item.nav-link.active span {
/* hot pink, bold text for active tab title */
color: #ff3399;
font-weight: bolder;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.