簡體   English   中英

將單獨的CSS應用於同一React自定義組件的多個實例之一

[英]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.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM