javascript - 根据 prop 有条件地添加元素

标签 javascript reactjs element prop

你应该如何有条件地添加像我下面这样的元素?我只要<div className='next-field__connected-wrapper'>存在于 withFilter 内 Prop 是正确的。

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

最佳答案

请记住,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>
  );
}

关于javascript - 根据 prop 有条件地添加元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32596939/

相关文章:

Javascript从路径中获取文件名和类型作为字符串

javascript - 引用引用 DOM 操作

java - 按特定元素对对象的 ArrayList 进行排序

php - 如何设置自定义错误消息 zend 表单元素文件?

java - 如何将 SVG 路径 (SVGOMPathElement) 转换为点数组?

javascript - 避免在视差滚动效果中对图像进行不必要的缩放

php - JavaScript 或 PHP 中的三向合并

reactjs - 预期属性简写

javascript - 创建 React 应用程序后,在 cmd 上 npm start 总是给出错误

javascript - React Hooks 多个带有单独倒计时的警报