有条件地添加基于道具的元素

时间:2015-09-15 22:49:36

标签: javascript reactjs element prop

你如何有条件地添加我下面的元素?如果<div className='next-field__connected-wrapper'>道具为真,我只希望withFilter存在。

  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>
      )
    }
  }

1 个答案:

答案 0 :(得分: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>
  );
}