使用三元运算符返回HTML

The*_*orm 1 html render ternary reactjs

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

{ this.state.showThanks ? 'Thanks for your response!' : null }
Run Code Online (Sandbox Code Playgroud)

但我想呈现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!' }
Run Code Online (Sandbox Code Playgroud)

我尝试了上述类似的操作,但出现错误,因此如何在我的react render方法中将html放在三元组中?

Rad*_*io- 5

像showThanks为true时三元表达式返回的内容一样,JSX元素始终需要一个父节点。您有两个输入-它们需要一个单亲,因此请将它们括在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!' }
Run Code Online (Sandbox Code Playgroud)

  • 我建议将三元表达式中间部分的“&lt;div&gt;”和“&lt;/div&gt;”分别替换为React的“&lt;Fragment&gt;”和“&lt;/Fragment&gt;”。您可以在 React 的导入中包含 `Fragment`:`import React, { Component, Fragment } from "react"`。它确保渲染的 HTML 不包含嵌套的 div(这有时会导致问题)。只是想我会把它放在那里。 (2认同)