我怎样才能使儿童道具价值超出反应地图

时间:2019-03-05 17:33:40

标签: reactjs next.js

如果任何子级具有“ acitve”类,我想在Panel上添加一个类。如果子元素变为“ active”类,如何添加“ parent-active”类。 谢谢您的帮助!

const MyComponent = ({
  router,
  className,
  items
}) => {

  return (
    <Collapse accordion={true}>
      {items.map(dropdown => {
        return (
          <Panel
            header={dropdown.title}
            headerClass="dropdown-title"
            className={router.pathname === item.href ? 'parent-active' : ''}
            key={dropdown.id}
          >
            {dropdown.dropdownItems.length}
            {dropdown.dropdownItems.map(item => (
              <Link href={item.href} key={item.id}>
                <a
                  className={
                    router.pathname === item.href ? 'active' : ''
                  }
                >
                  {item.label}
                </a>
              </Link>
            ))}
          </Panel>
        );
      })}
    </Collapse>
  );
};

export default withRouter(MyComponent);

1 个答案:

答案 0 :(得分:0)

我们可以使用Array.prototype.some()来确定是否有任何孩子将拥有active类:

const isAnyChildActive = dropdownItems.some((item) => router.pathname === item.href);

以及完整的代码段:

const MyComponent = ({
  router,
  className,
  items
}) => {

  return (
    <Collapse accordion={true}>
      {items.map(dropdown => {
        const { dropdownItems } = dropdown;
        const isAnyChildActive = dropdownItems.some((item) => router.pathname === item.href);

        return (
          <Panel
            header={dropdown.title}
            headerClass="dropdown-title"
            className={isAnyChildActive ? 'parent-active' : ''}
            key={dropdown.id}
          >
            {dropdown.dropdownItems.length}
            {dropdown.dropdownItems.map(item => (
              <Link href={item.href} key={item.id}>
                <a
                  className={
                    router.pathname === item.href ? 'active' : ''
                  }
                >
                  {item.label}
                </a>
              </Link>
            ))}
          </Panel>
        );
      })}
    </Collapse>
  );
};

export default withRouter(MyComponent);