【问题标题】:Passing an object prop to a React component in a mapping将对象道具传递给映射中的 React 组件
【发布时间】:2021-10-04 00:51:33
【问题描述】:

这可能是一个非常愚蠢的问题,但我使用这个 Nav Bar for Chakra UI 我发现并且我正在努力理解如何使用它。

这是我用来映射链接数组的数组和 NavLink 组件。

const Links = ['Dashboard', 'Projects', 'Team'];

const NavLink = ({ children }: { children: ReactNode }) => (
  <Link
    px={2}
    py={1}
    rounded={'md'}
    _hover={{
      textDecoration: 'none',
      bg: useColorModeValue('gray.200', 'gray.700'),
    }}
    href={'#'}>
    {children}
  </Link>
);

我应该如何将 href 传递给映射

Links.map((link) => (
                <NavLink key={link}>{link}</NavLink>

我尝试使用带有道具名称和 href 的对象,但我不知道如何将 href 道具传递给 NavLink。

请帮忙!

【问题讨论】:

    标签: javascript reactjs


    【解决方案1】:

    我猜你的链接是标签:

    const links = ["Dashboard", "Projects", "Team"];
    
    const NavLink = ({ children, href }: { children: ReactNode, href: string }) => (
      <Link href={href}>{children}</Link>
    );
    
    links.map((link) => (
      <NavLink key={link} href={`#${link}`}>
        {link}
      </NavLink>
    ));
    

    【讨论】:

      【解决方案2】:

      您可以将href 添加到NavLink 道具,并使用它来渲染Links 和href

      import * as React from "react";
      import { Link, useColorModeValue } from "@chakra-ui/react";
      
      const Links = ["Dashboard", "Projects", "Team"];
      
      const NavLink = ({
        children,
        href
      }: {
        children: React.ReactNode;
        href: string;
      }) => (
        <Link
          px={2}
          py={1}
          rounded={"md"}
          _hover={{
            textDecoration: "none",
            bg: useColorModeValue("gray.200", "gray.700")
          }}
          href={href}
        >
          {children}
        </Link>
      );
      
      export default function App() {
        return Links.map((link,i) => (
          <NavLink key={i} href={link}>
            {link}
          </NavLink>
        ));
      }
      

      示例如下:https://codesandbox.io/s/quizzical-feather-q0jd0

      【讨论】:

      • 谢谢,我试试看!
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2015-10-23
      • 2018-08-01
      • 2020-12-21
      • 2017-02-19
      • 1970-01-01
      • 1970-01-01
      • 2021-10-15
      相关资源
      最近更新 更多