首页 > 解决方案 > Change style of a child component using parent class from parent component's style file

问题描述

I have TrackCard component defined as:

<React.Fragment>
  {this.props.items.map((item, index) => (
    <div className={classes['genre-col']} key={index}> //<--------
      <div className={classes['track-single']}>
        <div className={classes['track-img-container']}>
          <img src={item.url} alt="" className={classes['track-image']} />
        </div>
        <div className={classes.genre}>
          <h6>{item.name}</h6>
          <p>{item.artist}</p>
        </div>
      </div>
    </div>
  ))}
</React.Fragment>

The genre-col class is defined in Music.scss

.genre-col {
    width: 20%;
}

Now I am accessing the TrackCard Component in another Component named Feeds as follows and the styles are defined in Feeds.scss :

<div className={`${classes['feed-cover']}`}>
    <TrackCard  items={this.state.tracks}/>
</div>

But here I need to change the width of the .genre-col without affecting other components. So I need to access .genre-col using the parent class in Feeds Component and define it in Feeds.scss.

I tried to import the style files in both the components and define the class globally. But there was no result.
I use SCSS modules for styling.

标签: htmlreactjssassjsxcss-modules

解决方案


Correct Me if I'm wrong. As I understood, What you want is to control TrackCard from Feeds Component. There are few ways to do that.

1. Create a class in Feeds.css and pass it to TrackCard like below

<TrackCard  items={this.state.tracks} customClass={classes['track-card']}/>

and Inside TrackCard

{this.props.items.map((item, index) => (
     <div className={classnames(classes['genre-col'], this.props.customClass)} key={index}> />

classnames is a library for the doing class concatenation and stuff easily. Have a look at the library.

2.Define different classes which represents various sizes, you want, inside Music.scss itself. Pass a prop from Feeds like in below code.

.small { width: 300px; }
.medium { width: 500px; }
.large { width: 800px; }

For TrackCard pass needed size as props.

<TrackCard  items={this.state.tracks} size={'medium'}/>

and Inside TrackCard

{this.props.items.map((item, index) => (
     <div className={classnames(classes['genre-col'], classes[this.props.size])} key={index}> />

推荐阅读