在自定义 React 元素上添加样式属性似乎没有成功

Adding style attribute on custom React element does not seem to pick up

我有如下代码(使用 CSS 模块):

return (
  <div>
    <LandingPage className={styles.hidden} />
  </div>
);

这不起作用(即不将 CSS 应用于元素)。然而,返回

  <div>
    <div className={styles.hidden}>
      <LandingPage />
    </div>
  </div>

工作正常。为什么在自定义元素上应用 className 会导致 class 被忽略?

这里的className不会直接应用在LandingPage组件上,它基本上是一个从父组件传给子组件的props值,你需要应用那个class 在 LandingPage 组件内。

像这样:

<LandingPage customClassName={styles.hidden} />

里面 LandingPage:

render(){
   console.log('class name', this.props.customClassName);
   return(
       <div className={this.props.customClassName}>
           {/* other elements */}
       </div>
   )
}

永远记住 props 是一个对象,无论你从父组件传递的什么数据都只会成为 props 值的一部分,你需要在子组件的某个地方使用该数据。

检查 console,它将打印您从父级传递的正确 class 名称。