【问题标题】:How to render jsx correctly如何正确渲染 jsx
【发布时间】:2018-01-02 07:59:47
【问题描述】:
<div className="feedback">
    {(this.state.finished) ? questions.map(function(x, index) { return
    <div>
    </div>
    }) : null}
</div>      

所以我现在有上面的代码。我想添加另一段类似 this.state.score 的 js 代码,但不在 map 函数中,因为我只希望它渲染一次(目前它每次映射到数组时都会渲染)

<div className="feedback">
    {(this.state.finished) ? {this.state.score} //WANT TO ADD IT HERE questions.map(function(x, index) { return
    <div>
    </div>
    }) : null}
</div>

但这不起作用。那么如何在此块中添加我的代码?我也需要它在三元中

【问题讨论】:

    标签: arrays reactjs jsx


    【解决方案1】:

    JSX 中的三元表达式必须返回数组或单个节点,类似于 React 的 render 方法必须只返回单个节点。

    <div className="feedback">
        { (this.state.finished) ?
          <div>
            {this.state.score}
            {questions.map(function(x, index) {
              return <div></div>
            })}
          </div>
          :
          null
        }
    </div>
    

    现在,三元生成单个节点(&lt;div&gt;),它基本上“包装”了您想要有条件地渲染的所有内容。另外,请注意 questions.map 被包裹在花括号 {} 中,因为您将内联 JavaScript 嵌套在 JSX 内部甚至更多的内联 JavaScript 中。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-10-12
      • 2020-06-28
      • 2019-02-21
      • 2020-05-27
      • 2018-01-25
      • 2020-10-12
      • 2017-01-18
      相关资源
      最近更新 更多