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

被刻印的时光 ゝ 提交于 2019-12-06 11:39:23

问题


I have code as follows (using CSS modules):

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

Which doesn't work (i.e. doesn't apply the CSS to the element). However, returning

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

Works just fine. Why does applying a className on a custom element cause the class to be ignored?


回答1:


Here className will not get applied directly on LandingPage component, it is basically a props value that you are passing from parent component to child component, you need to apply that class inside LandingPage component.

Like this:

<LandingPage customClassName={styles.hidden} />

Inside LandingPage:

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

Always remember props is an object, whatever data you will pass from parent will become a part of props values only, you need to use that data somewhere in child component.

Check the console, it will print the proper class name that you are passing from parent.



来源:https://stackoverflow.com/questions/44573292/adding-style-attribute-on-custom-react-element-does-not-seem-to-pick-up

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!