【问题标题】:Conditionally add element based on prop根据 prop 有条件地添加元素
【发布时间】:2015-09-15 22:49:36
【问题描述】:

您应该如何有条件地添加如下所示的元素?如果withFilter 属性为真,我只希望<div className='next-field__connected-wrapper'> 存在于其中。

  render: function () {
    if (this.props.withFilter) {
      return (
        <div>
          <div className='next-card next-card__section next-card__section--no-bottom-spacing'>
            <div className='next-field__connected-wrapper'>
              { this.props.children }
            </div>
          </div>
        </div>
      )
    } else {
      return (
        <div>
          <div className='next-card next-card__section next-card__section--no-bottom-spacing'>
            { this.props.children }
          </div>
        </div>
      )
    }
  }

【问题讨论】:

    标签: javascript reactjs element prop


    【解决方案1】:

    请记住,JSX 元素只是 JavaScript 对象,您可以将它们分配给变量并像其他任何东西一样传递它们:

    render: function () {
      let inner = this.props.children;
    
      if (this.props.withFilter) {
        inner = (
          <div className='next-field__connected-wrapper'>
            {inner}
          </div>
        );
      }
    
      return (
        <div>
          <div className='next-card next-card__section next-card__section--no-bottom-spacing'>
            {inner}
          </div>
        </div>
      );
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-09-09
      • 2022-10-14
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-06-30
      • 2017-08-10
      相关资源
      最近更新 更多