【问题标题】:Using a ternary operator to return HTML使用三元运算符返回 HTML
【发布时间】:2017-03-28 05:49:51
【问题描述】:

我知道如何使用这样的三元运算符:

{ this.state.showThanks ? 'Thanks for your response!' : null }

但我想渲染 html,然后在点击时删除该 html

    { this.state.showThanks ? <input type="submit" className="decisionButtons" id="canDecisionButton" value="I can play" onClick={() => this.canPlay()}/>
                <input type="submit" className="decisionButtons" id="cantDecisionButton" value="I cannot play" onClick={() => this.cannotPlay()}/>
  : 'Thanks for your response!' }

我尝试了类似上述的方法,但出现错误,那么如何在我的 react 渲染方法中将 html 放置在三元组中?

【问题讨论】:

    标签: html reactjs render ternary


    【解决方案1】:

    JSX 元素,例如当 showThanks 为真时返回的三元表达式,总是需要一个父节点。您有两个输入 - 它们需要一个父级,因此将它们包含在一个 div 中。

    { this.state.showThanks ? 
    <div>
        <input type="submit" className="decisionButtons" id="canDecisionButton" value="I can play" onClick={() => this.canPlay()}/>
        <input type="submit" className="decisionButtons" id="cantDecisionButton" value="I cannot play" onClick={() => this.cannotPlay()}/>
    </div>
      : 'Thanks for your response!' }
    

    【讨论】:

    • 我建议将三元表达式中间部分的&lt;div&gt;&lt;/div&gt; 分别替换为React 的&lt;Fragment&gt;&lt;/Fragment&gt;。你可以在 React 的导入中包含 Fragmentimport React, { Component, Fragment } from "react"。它确保呈现的 HTML 不包含嵌套的 div(这有时会导致问题)。只是想我会把它放在那里。
    • 这是否适用于多个 div 或 div & br 的组合
    猜你喜欢
    • 2018-07-24
    • 1970-01-01
    • 2012-08-28
    • 2020-02-09
    • 1970-01-01
    • 1970-01-01
    • 2018-01-26
    • 2020-01-25
    相关资源
    最近更新 更多