【问题标题】:React remove last url from anchor inside liReact 从 li 内的锚点中删除最后一个 url
【发布时间】:2020-01-03 09:55:21
【问题描述】:

我想删除 React 列表中的锚标记 (href="") 的最后一个 url。

这是我的代码:

const Link = ({ ...props }) => <TranslationsLink {...props} />;

const Navbar: FC<Props> = () => {
  return (
    <Nav>
      <List>
        {list.map((el, i) => {
          const lastEl = i === list.length - 1;

          return (
            <Item key={el.route}>
              <Link
                lastEl={lastEl}
              >
                {el.text}
              </Link>
            </Item>
          );
        })}
      </List>
    </Nav>
  );
};

const TranslationsLink: FC<ITranslationsLink> = memo(({ ...props }) => {
  const { findRouteByName, activeLocale } = useRouter();

  const routeMatch = findRouteByName(route, locale || activeLocale);

  const url = routeMatch.getUrl(params);
  const nextLink = routeMatch.getNextLink(params);

  const link = (
    <a href={url} {...props}>
      {children}
    </a>
  );

  return <Link href={nextLink} as={url} children={link} />;
});

我尝试将 lastEl 传递给 Link 组件,以便覆盖它的 href:

&lt;Link href={props.lastEl ? '' : nextLink}

问题在于,因为它在其他地方被使用了同一个链接,所以我弄错了......如果不为最后一个元素创建另一个链接组件,我该如何避免这种情况?

【问题讨论】:

    标签: reactjs


    【解决方案1】:

    您可以像这样向地图添加条件:

    const Navbar: FC<Props> = () => {
      return (
        <Nav>
          <List>
            {list.map((el, i) => {
              const lastEl = i === list.length - 1;
    
              return lastEl ? null : // just check for the lastEl here
                (<Item key={el.route}>
                  <Link
                    lastEl={lastEl}
                  >
                    {el.text}
                  </Link>
                </Item>
              );
            })}
          </List>
        </Nav>
      );
    };
    

    【讨论】:

    • 我根据您的回复找到了答案,我需要返回的不是 null,因为文本必须出现在该 li 元素上
    【解决方案2】:

    我找到了答案:

    const Navbar: FC<Props> = () => {
      return (
        <Nav>
          <List>
            {list.map((el, i) => {
              const lastEl = i === list.length - 1;
    
              return
                (<Item key={el.route}>
                {lastEl ? (
                    <span>{el.text}</span>
                  ) : (
                    <Link>
                      {el.text}
                    </Link>
                  )}
                </Item>
              );
            })}
          </List>
        </Nav>
      );
    };

    【讨论】:

      猜你喜欢
      • 2019-09-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-22
      • 2015-03-09
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多