[英]Apply separate CSS to one of the multiple instances of same React custom component
我有兩個名為Grid和FieldValue的自定義組件,我在特定頁面上多次使用FieldValue組件。 我使用所謂的類名.black
所有fieldValue方法組件。 現在,我想使用一個名為.blue-pointer
的不同類名,其中.blue-pointer
中的數據表示view2。 請幫我理解如何做到這一點。
頁面上的組件如下所示
<Grid>
<FieldValue data={'view1'}/>
<FieldValue data={'view2'}/>
<FieldValue data={'view3'}/>
</Grid>
FieldValue的定義如下,
class FieldValue extends React.Component<>{
render(){
<div className="black">
{'testView'}
</div>
}
}
CSS的定義如下
.black{
color:#4d546d;
}
.blue-pointer {
color: #0070d2;
cursor: pointer;
}
使用組件中的props
:
class FieldValue extends React.Component{
render() {
return (
<div className={this.props.data === 'view2' ? 'blue-pointer' : 'black'}>
{'testView'}
</div>
);
}
}
您可以將className
定義為prop
,並為其指定默認值'black'
。
class FieldValue extends React.Component<> {
static defaultProps = {
className: 'black'
}
render() {
const { className } = this.props
<div className={className}>
{'testView'}
</div>}
}
對於默認情況,您無需更改任何內容:
<FieldValue data={'view1'} /> // Still uses the `black` style.
如果要更改類名,請使用:
<FieldValue data={'view2'} className='blue-pointer' />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.