【问题标题】:Components with 'Variants' in React - Conditional RenderingReact 中带有“变体”的组件 - 条件渲染
【发布时间】:2018-08-13 13:54:42
【问题描述】:

这里是一个非常基本的问题。

我正在尝试开始学习 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>
    );
  }
}
}

【问题讨论】:

  • button-wrapper ${ variant === 'secondary' ? '' : 'primary' }}>

标签: reactjs rendering


【解决方案1】:

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

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

【讨论】:

  • 不应该是&lt;div className = {`button-wrapper ${variant}`}&gt;吗?
  • @ArslanTariq 原来的帖子是为次要变体设置空的类名。你是对的,如果变体正是作者想要用于类名的。
  • @JeeMok 我有同样的问题要问你,但这将与它里面的组件有关,所以我有一个Component A 返回Components B, C,但在概率结构中,即@987654326 @实现这一目标的最佳方法是什么?
猜你喜欢
  • 1970-01-01
  • 2018-09-10
  • 1970-01-01
  • 2018-12-20
  • 1970-01-01
  • 2021-06-07
  • 2017-05-21
  • 2021-05-26
  • 1970-01-01
相关资源
最近更新 更多