具有多种情况和复杂逻辑的条件渲染功能组件

时间:2019-08-13 15:06:27

标签: reactjs conditional-statements react-hooks

我是React的新功能组件和新的Hook功能。目前,我有一个具有复杂逻辑和多种情况的条件渲染用例(不能简单地使用切换用例,三进制或枚举渲染)。查看下面的示例代码:

const conditionRender = condition => {
  if (condition < 0) {
    return <Component1 />
  }
  if (condition < 12) {
    return <Component2 />
  }
  if (condition < 50) {
    return <Component3 />
  }
  if (condition < 100) {
    return <Component4 />
  }
  if (condition % 2 === 0) {
    return <Component5 />
  }
}

function App() {
  return (
    <div className="App">
    {conditionRender(condition)}
    </div>
  );
}

我正在使用功能外部的功能组件。这是最佳做法吗?或者您可以为此建议最好。谢谢

1 个答案:

答案 0 :(得分:0)

最后只返回一个空值,因为如果没有一个条件匹配,那么它将不返回任何内容

const conditionRender = condition => {
  if (condition < 0) {
    return <Component1 />
  }
  if (condition < 12) {
    return <Component2 />
  }
  if (condition < 50) {
    return <Component3 />
  }
  if (condition < 100) {
    return <Component4 />
  }
  if (condition % 2 === 0) {
    return <Component5 />
  }
return null
}