简体   繁体   English

如果 Map 内部的条件 // React JS

[英]If condition inside Map // React JS

I'm working on a Breadcrumb component in React JS that returns Links.我正在研究返回链接的 React JS 中的 Breadcrumb 组件。 When binding the component inside my header I give it an array of items (label for the link, URL and a class for 'active' or 'inactive').在我的 header 中绑定组件时,我给它一个项目数组(链接标签 URL 和 class 用于“活动”或“非活动”)。

Now, inside the mapping of this data I would like to check whether or not the class is 'inactive', and if that is the case I want to set the 'to' link (to={to}) to an empty string.现在,在此数据的映射中,我想检查 class 是否“无效”,如果是这种情况,我想将“到”链接(to = {to})设置为空字符串。 I have unsuccessfully tried using an if condition around the ≤Link≥ component, does anyone know if this is possible and what the correct syntax is?我没有成功尝试在 ≤Link≥ 组件周围使用 if 条件,有谁知道这是否可行以及正确的语法是什么?

const items = [
    {to: '/link1', label: 'Step 1', stepClass: 'active'},
    {to: '/link2', label: 'Step 2', stepClass: 'inactive'},
];

<Breadcrumb>
      {items.map(({to, label, stepClass}) => (
        <Link key={to} to={to}>
          <div className={`step ${stepClass}`}>{label}</div>
        </Link>
      ))}
 </Breadcrumb>

Maybe something like也许像

const items = [
    {to: '/link1', label: 'Step 1', stepClass: 'active'},
    {to: '/link2', label: 'Step 2', stepClass: 'inactive'},
];

<Breadcrumb>
      {items.map(item => (
        <Link key={item.to} to={item.stepClass == active ? item.to : ''}>
          <div className={`step ${item.stepClass}`}>{label}</div>
        </Link>
      ))}
 </Breadcrumb>

You can also use if-else block like this in react and return jsx from if-else block.您还可以在反应中使用 if-else 块,并从 if-else 块返回 jsx。

const items = [
    {to: '/link1', label: 'Step 1', stepClass: 'active'},
    {to: '/link2', label: 'Step 2', stepClass: 'inactive'},
];

<Breadcrumb>
      {items.map(({to, label, stepClass}) => {
        if(stepClass === "inactive")
         {
            return (
                    <Link key={to} to={to}>
                        <div className={`step ${stepClass}`}>{label}</div>
                    </Link> 
                 );
         }
         else 
         {
              return (

                // code here
              );
          }

      })}
 </Breadcrumb>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM