将单独的CSS应用于同一React自定义组件

时间:2018-03-21 08:50:43

标签: css reactjs react-native

我有两个名为Grid和FieldValue的自定义组件,我在特定页面上多次使用FieldValue组件。我正在为所有FieldValue组件使用名为.black的类名。现在,我想使用一个名为.blue-pointer的不同类名,其中FieldValue中的数据表示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;
}

2 个答案:

答案 0 :(得分:2)

使用组件中的props

class FieldValue extends React.Component{
  render() {
    return (
      <div className={this.props.data === 'view2' ? 'blue-pointer' : 'black'}>
        {'testView'}
      </div>
    );
  }
}

答案 1 :(得分:0)

您可以将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' />