我怎样才能在反应地图之外获得 children 道具值

How can i get children props value outside react map

如果 child 有 'acitve' class,我想在面板上添加一个 class。如果 child 元素得到 'active' class,如何添加 'parent-active' class。 感谢您的帮助!

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);

我们可以使用 Array.prototype.some() 来确定 children 中是否有一个 active class:

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);