问题
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