html - 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.
解决方案
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}> />
推荐阅读
- sql - 在SQL中按某列分组后如何按日期聚合总和过滤计算?
- r - 无法在 R 中将数字转换为日期
- oracle - 为什么我收到错误消息 PLS-0382:表达式类型错误
- ios - iOS 上的 Flutter 崩溃 - io.flutter.1.ui EXC_BAD_ACCESS KERN_INVALID_ADDRESS 0x0000000000000000
- python - 在另一列中查找最接近的匹配项
- git - ATOM 不显示文件夹/文件中的更新,也不显示 GIT repo 更新
- c# - 无法让 SQL 客户端在二进制 powershell 模块中工作
- mongodb - [错误:Query.gameWeeks 在解析器中定义,但不在模式中]
- postgresql - tar.gz 上的 PostreSQL pg_archivecleanup
- crystal-reports - Crystal Reports 数字格式(仅显示数据库中的数字。)