【问题标题】:Problems with Rendering Component in React + TypescriptReact + Typescript 中渲染组件的问题
【发布时间】:2020-09-18 20:37:55
【问题描述】:

我正在尝试将某些内容渲染到我的屏幕上,但目前它没有显示出来。我知道该函数正在输入 if 条件,因为我使用控制台日志记录对其进行了测试。

这里是我写条件渲染特定内容的地方。

renderContent = (): Content => {
  this.props.contents.forEach((content:SomeType) => {
    if (content.booleanCondition){
      return <ImportantComponent contentData = {this.usefulFunction()}/>
    }
  }
}

这里是我想要渲染所有内容的地方。

renderEverything = () => {
  return (
    {this.renderContent()}
  );
};

或者,有没有一种方法可以直接在 renderEverything 中编写条件,这样我就不必调用函数 renderContent?

【问题讨论】:

  • 这两个函数是否在同一个文件中,顺便说一下,您能否添加更多源代码来帮助您?也许错误不存在而您错过了它

标签: javascript reactjs typescript conditional-statements render


【解决方案1】:

如果你想为每个满足booleanCondition的内容元素渲染一个ImportantComponent:

renderEverything = () => {
  return this.props.contents.map(
      content => content.booleanCondition && <ImportantComponent key={content} contentData = {this.usefulFunction()}/>
  )
}

如果任何内容元素满足 booleanCondition 时,您只想渲染一个重要组件:

renderEverything = () => {
  const contentToBeShown = this.props.contents.find(content => content.booleanCondition)
  if(contentToBeShown)
     return <ImportantComponent contentData = {this.usefulFunction()}/>
}

【讨论】:

    猜你喜欢
    • 2021-03-30
    • 1970-01-01
    • 2022-10-21
    • 2021-07-22
    • 2023-04-04
    • 2020-01-16
    • 2019-03-01
    • 2021-08-21
    • 1970-01-01
    相关资源
    最近更新 更多