我有一個h3帶有深灰色文本顏色的反應組件。我想在背景顏色也是深灰色的地方重用組件,所以我需要將h3文本顏色更改為更淺的顏色。
這是組件在我需要更改某些區域的文本顏色之前的狀態:
// other imports
import styles from "./styles/subheader.module.css"
export default function Subheader(props) {
return (
<Container>
<h3 className={styles.h3}>{props.text}</h3>
<div className={styles.headerUnderline}></div>
</Container>
)
}
CSS:
.h3 {
font-family: var(--font-family);
font-size: var(--h3-font-size);
text-align: center;
color: rgb(33, 37, 41);
margin-top: 2rem;
}
.headerUnderline {
width: 100px;
height: 4px;
background-color: rgb(219, 190, 157);
margin: 0 auto;
border-radius: 2px;
margin-bottom: 2rem;
}
我試過這個沒有用:
<Subheader text="PRODUCTS" style={{color: "rgb(219, 190, 157)"}} />
所以我嘗試傳遞道具并更改我的組件:
//other imports
import styles from "./styles/subheader.module.css"
export default function Subheader(props) {
return (
<Container>
<h3 className={styles.h3 " " props.lightText ? styles.lightText : styles.darkText}>{props.text}</h3>
<div className={styles.headerUnderline}></div>
</Container>
)
}
并更改了 CSS:
.h3 {
font-family: var(--font-family);
font-size: var(--h3-font-size);
text-align: center;
margin-top: 2rem;
}
.lightText {
color: rgb(219, 190, 157);
}
.darkText {
color: rgb(33, 37, 41);
}
并使用如下:
// both render light text with no .h3 styling like centered text
<Subheader text="WE DELIVER" lightText={true} />
<Subheader text="PRODUCTS" lightText={false} />
但這也不起作用。
uj5u.com熱心網友回復:
如果您將h3 className更改為模板字串,它將起作用:
<h3 className={`${styles.h3} ${props.lightText ? styles.lightText : styles.darkText}`}>{props.text}</h3>
或至少它的最后一部分:
<h3 className={styles.h3 " " `${props.lightText ? styles.lightText : styles.darkText}`}>{props.text}</h3>
在這里你可以找到很多關于如何添加多個類名的很好的例子:如何將多個類添加到 ReactJS 組件?
uj5u.com熱心網友回復:
你可以style像這里一樣使用prop:
<Subheader text="PRODUCTS" style={{color: "rgb(219, 190, 157)"}} />
但是請注意,您不是將styleprop傳遞給元素,而是傳遞給組件,因此,例如text,可以在props物件上的組件內部訪問它(即props.style)。
這是您可以訪問的方式style:
export default function Subheader(props) {
return (
<Container>
<h3 style={props.style} className={styles.h3}>{props.text}</h3>
<div className={styles.headerUnderline}></div>
</Container>
)
}
實體:代碼沙盒
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/354958.html
