如何在 NavLink v6 中布置动态子项

How to lay out dynamic children in NavLink v6

NavLink 中,我试图将 isActive 属性作为子函数传递给函数,并且还让我的 link 的名称是动态的。

我收到多个错误,我不确定自己做错了什么(我是 React 的新手)。

import { NavLink } from 'react-router-dom';

const navigation = [
  { name: 'Home', href: '/', icon: HomeIcon, current: true },
  { name: 'Users', href: '/Users', icon: UsersIcon, current: false }
]

function classNames(...classes: string[]) {
  return classes.filter(Boolean).join(' ')
}

export class Nav extends Component<any, any> {
  
  constructor(props: boolean) {
    super(props);
  }
  
  render() {
    return (
      <>
        <nav className="mt-5 flex-1 px-2 space-y-1">
          {navigation.map((item) => (
            <NavLink
              key={item.name}
              to={item.href}
            >
              {({ isActive }) => (
                <item.icon
                  className={classNames(
                    isActive ? 'text-gray-300' : 'text-gray-400 group-hover:text-gray-300',
                    'mr-3 flex-shrink-0 h-6 w-6'
                  )}
                  aria-hidden="true"
                />
                {item.name}
              )}
            </NavLink>
          ))}
        </nav>
      </>
    );
  }
}

NavLink 组件上我得到:

This JSX tag's 'children' prop expects a single child of type 'ReactNode | ((props: { isActive: boolean; }) => ReactNode)', but multiple children were provided.

在 item.name 行我得到:

Parsing error: ')' expected.

在关闭 NavLink 之前的最后一个关闭花括号中,我得到:

Unexpected token. Did you mean {'}'} or &rbrace;?

This JSX tag's 'children' prop expects a single child of type 'ReactNode | ((props: { isActive: boolean; }) => ReactNode)', but multiple children were provided.

item.iconitem.name 包装在 React.Fragment 中,因为您不能 return 来自一个函数的多个子项。例如:-

<>
<item.icon className={classNames(isActive ? 'text-gray-300' : 'text-gray-400 group-hover:text-gray-300','mr-3 flex-shrink-0 h-6 w-6')} aria-hidden="true" />
                      {item.name}</>

React 组件应该return 单个节点元素。将 returned JSX 包装在 React.Fragment 组件中。

示例:

<NavLink
  key={item.name}
  to={item.href}
>
  {({ isActive }) => (
    <>
      <item.icon
        className={classNames(
          isActive
            ? 'text-gray-300'
            : 'text-gray-400 group-hover:text-gray-300',
          'mr-3 flex-shrink-0 h-6 w-6'
        )}
        aria-hidden="true"
      />
      {item.name}
    </>
  )}
</NavLink>