React中带有“变量”的组件-条件渲染

时间:2018-08-13 13:54:42

标签: reactjs rendering

这里很基本的问题。

我正试图开始学习React,我对进行此类事情的最佳设计模式感到好奇。

我有一个按钮组件,我想要该组件的“主要”和“次要”变体应用不同的类。以下是实现该目标的最佳方法吗?我正在传递一个“变体”道具,该道具定义了要使用的按钮。

如果这不是最好的解决方案,那么如果我想要特定组件的“变体”,那该怎么办。

谢谢!

class Button extends Component {

render() {

  // --- SECONDARY BUTTON --- //
  if(this.props.variant == 'secondary') {

    return (
      <div className = 'button-wrapper secondary'>
        <div className = 'button'>
          {this.props.text}
        </div>
      </div>
    );

  // --- PRIMARY BUTTON --- //
  }else if(this.props.variant == 'primary') {

    return (
      <div className = 'button-wrapper primary'>
        <div className = 'button'>
          {this.props.text}
        </div>
      </div>
    );
  }
}
}

1 个答案:

答案 0 :(得分:0)

如果您的区别仅在于className,也许您可​​以通过以下方式实现相同目的:

render() {
 const { variant } = this.props;
 return (
   <div className = {`button-wrapper ${ variant === 'secondary' ? '' : 'primary' }`}>
     <div className = 'button'>
       {this.props.text}
     </div>
   </div>
 );
相关问题