【问题标题】:What's the correct syntax for if conditional when working with calling components in React + Typescript?在 React + Typescript 中使用调用组件时,if 条件的正确语法是什么?
【发布时间】:2020-09-18 04:33:36
【问题描述】:

我目前正在尝试显示一个组件并仅在其状态属性之一为真时将函数作为道具传递。但是,我遇到了语法问题。这是我所拥有的:

render = () => {
return (
  <ParentComponent>

       {if (this.onlyRenderIfTrue) {
          <ChildComponent prop1={this.usefulFunction()}/>
       }}

  </ParentComponent>
);

}

JSX 让我有点困惑。我知道每当我必须使用 Javascript 时,我都必须将它放在 {} 中,但是对于像这样更嵌套的东西,它让我有点失望。

【问题讨论】:

标签: reactjs typescript jsx tsx


【解决方案1】:

你不能直接在 React 渲染钩子中编写条件语句。但是,您可以使用 &amp;&amp; 运算符或 ternary 运算符:

render = () => {
  return (
   <ParentComponent>
   {
      this.onlyRenderIfTrue &&
      <ChildComponent prop1={this.usefulFunction()}/>
   }
   </ParentComponent>
  );
}

如果你想使用条件语句,那么你可以定义如下函数:

const renderComponent = () => {
  if (somethingIsTrue) {
   return <h1>True</h1>
  } else {
   return <p>False</p>
  }
}

现在,在您的组件渲染中,您可以调用:

{renderComponent()}

【讨论】:

  • 可能只是一个错误,但您错过了 this.onlyRenderIfTrue &amp;&amp; 周围的 {} 部分。
猜你喜欢
  • 1970-01-01
  • 2021-11-03
  • 1970-01-01
  • 2020-08-21
  • 2017-06-05
  • 2021-02-07
  • 1970-01-01
  • 1970-01-01
  • 2011-01-24
相关资源
最近更新 更多