首页 > 解决方案 > 如何将道具传递给反应组件以更改文本颜色

问题描述

我有一个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} />

但这也没有用。

标签: cssreactjsreact-bootstrapreact-props

解决方案


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>
  )
}

实时示例:代码沙箱


推荐阅读