css - 如何将道具传递给反应组件以更改文本颜色
问题描述
我有一个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} />
但这也没有用。
解决方案
style
你可以像在这里一样使用prop:
<Subheader text="PRODUCTS" style={{color: "rgb(219, 190, 157)"}} />
但是请注意,您不是将style
prop 传递给元素,而是传递给组件,因此,就像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>
)
}
实时示例:代码沙箱
推荐阅读
- javascript - 合并 3 个订阅数据以加入新对象 rxjs Angular 9 中的数据
- mongodb - 从数组中获取日期最大的项目值
- python - Tkinter 变量未更新
- parsing - 列号不一致时如何使用 AWK 解析值
- python - 通过公司防火墙安装 python(Spyder 和 Python)
- python - Python Pytrends数据在输入一段时间后丢失
- javascript - 在 React js 中更改状态嵌套对象的值 - 映射函数不起作用
- javascript - PHP`s hash_hmac() 是否有任何等效的 JavaScript 函数?
- docker - Docker Pull - 注册层失败:只读文件系统
- r - 如何计算R中单列中特定值的出现次数