有条件地渲染组件

时间:2021-07-27 09:58:22

标签: javascript reactjs

import Home from "./home";
import About from "./about";
import Contact from "./contact";

const Funks = [
  {
    component: Home,
    label: "Home",
    isActive: true
  },
  {
    component: About,
    label: "About",
    isActive: false
  },
  {
    component: Contact,
    label: "Contact",
    isActive: false
  }
];

export default class Funky extends Component {
  render() {
    return (
      {Funks.map(({ component, isActive}) => isActive ? /* how to render component? */ : null )}
    )
  }
}

如何使用 component 参数渲染组件?我是 React 的新手,所以任何提示都会有所帮助。

谢谢!

2 个答案:

答案 0 :(得分:2)

您需要更新数组中的组件值,如下所示以呈现这些组件;

const Funks = [
  {
    component: <Home />,
    label: "Home",
    isActive: true
  },
  {
    component: <About />,
    label: "About",
    isActive: false
  },
  {
    component: <Contact />,
    label: "Contact",
    isActive: false
  }
];

然后映射数组并按如下方式输出,这将输出您的组件。

return Funks.map((item) => (item.isActive ? item.component : null));

请注意,根据命名约定,组件文件名必须以首字母大写开头。

答案 1 :(得分:1)

TABS.map 应该是 Funks.map 我假设。

现在替换 /* 如何渲染组件? */ 与:

(component === 'Home')? <Home/> : (component ==='About') ? <About/> : <Contact/>

这将修复您当前的代码。但这并不是呈现组件的理想方式。