如果为true,则React显示这些div

ico*_*ode 3 javascript jsx reactjs

我仍然对React还是陌生的,很难尝试弄清楚如果props返回true时如何显示div元素的内容。我知道我只能在一个函数中返回一个渲染,但是我该如何实现。我可以编写一些类型的Jsx内联if语句吗?

<div>if true show</div> 
<div>if true show</div> 
<div>false don't show</div> 
<div>if true show</div> 
Run Code Online (Sandbox Code Playgroud)

更新:我实际上用过

{this.props.test === true &&
    <div>if true show</div>
  }
Run Code Online (Sandbox Code Playgroud)

spe*_*arp 6

如果您正在寻找简明扼要的内容,尽管不一定更易读,您可以使用三元运算符。

{this.props.test ? <div>if true show</div> : ''}
Run Code Online (Sandbox Code Playgroud)


Aak*_*ash 5

您可以通过以下两种方法实现所需的目标:

1)这有点冗长,但是它允许您将逻辑轻松拆分为较小的,集中的块。

maybeRenderPerson: function() {
    var personName = ...;
    if ( personName ) {
        return <div className="person">{personName}</div>;
    }
}

render: function() {
    return (
       <div className="component">
          {this.maybeRenderPerson()}
       </div>
    );
}
Run Code Online (Sandbox Code Playgroud)

2)如果测试的变量可能是伪造的值,例如0,“”或false,则此语法可能非常危险。特别是对于数字,如果要确保测试结果为0,应该宁愿稍微修改一下测试。

render: function() {
    var person= ...; 
    var counter= ...; 
    return (
        <div className="component">
          {person && (
            <Person person={person}/>
         )}
         {(typeof counter !== 'undefined') && (
             <Counter value={counter}/>
         )}
       </div>
    );
}
Run Code Online (Sandbox Code Playgroud)

Matt建议的驴子,您可以在这里找到有关条件渲染的更多信息。


ico*_*ode 5

现在简单的用例。

{this.props.test === true &&
    <div>if true show</div>
  }
Run Code Online (Sandbox Code Playgroud)