在反应中,我该如何做一个if语句

时间:2019-06-17 10:59:11

标签: javascript reactjs

我对此有反应:

return (
   <p title={ 'name' }> TEST </p>
)

我想在if内做一个return语句。我对此进行了测试:

return (
   <p title={ 'name' }> TEST </p>
   if (variable) {
      <p> hello </p>
   } else {
      <p> world </p>
   }
)

很明显,我不知道自己在做什么。正确的方法是什么?抱歉入门级问题。

6 个答案:

答案 0 :(得分:3)

您可以使用ternary operator (?),并且还必须具有包装器元素以包含两个单独的段落(标题和内容),因此简单的返回将是:

render() {

    return (
        <div>
            <p title={'name'}> TEST </p>
            <p> { variable ? "hello" : "world" } </p>
        </div>
    )
}

出于可读性考虑,最好将“单线”分开:

// ...
<p>
{ 
    variable ? (
        <em style={{color: 'black'}}>hello</em>
    ) : (
        <em>world</em> 
    )
}
</p>
// ...

但是,它并不总是那么简单,因此我建议使用一个占位符变量,例如:

render() {

    var $content;
    if(variable) {
        $content = (<p>hello</p>);
    }
    else {
        $content = (<p>world</p>);
    }


    return (
        <div>
            <p title={'name'}> TEST </p>
            {$content}
        </div>
    )
}

答案 1 :(得分:0)

错误是使用JSX语法而不是if-statement

return (
   <>
   <p title={ 'Publish Checklist' }> TEST </p>
    {
        variable ? <p> hello </p>: <p> world </p>
    }
   </>
)

答案 2 :(得分:0)

您可以使用三元条件运算符(?)

return (
   <p title={ 'Publish Checklist' }> TEST </p>
   {
      variable?<p> hello </p>:<p> world </p>
   }
)

答案 3 :(得分:0)

您必须使用三元运算符:

   {variable ?
      <p style={{ color: 'black'}}> Hello</p> 
   :
      <p> world </p>
   }

冒号: ---> or你好or世界

看这里:https://codepen.io/gaearon/pen/Xjoqwm?editors=0010

文档反应渲染:https://reactjs.org/docs/conditional-rendering.html

如果variabletrue,则返回<p> hello </ p>,如果false返回<p> world </ p>

答案 4 :(得分:0)

您要使用ternary operator。它的作用与if / else语句相同,其中?是if,:是else:

condition
  ? // code where condition is true
  : // code where condition is false

这是实现它的方法:

return (
   <>
     <p title='name'> TEST </p>
     {variable ? <p> hello </p> : <p> world </p>}
   </>
)
  

注意,我注意到您使用了title={'name'}。这可以正常工作,但是您可以将其编写为普通的html:title='name'。此外,反应组件在渲染时仅采用一个子组件,因此您可以将返回的节点包装在反应片段中或仅包装div。

答案 5 :(得分:-1)

您可以在react中使用条件渲染。在此处了解更多信息:https://reactjs.org/docs/conditional-rendering.html

在您的情况下,三元运算符会很好地工作。其语法如下:

condition ? if : else

在您的情况下,您可以这样使用它:

return (
   <p title={ 'name' }> TEST </p>
  {variable ?
      <p> hello </p>
   :
      <p> world </p>
   }
)