警告:validateDOMNesting(...):<a> 不能作为<a> 的后代出现

4
我正在使用React路由器DOM Link组件,它类似于Twitter的主页动态。我想在一个div组件中能够有两种类型的链接。一种是链接到用户的个人资料,另一种是链接到帖子。目前我正在收到警告并且无法找到解决方案。以下是参考截图: enter image description here 我理解这里的问题,我的post链接是父元素,我在其中添加了两个user链接组件,因为当用户点击帖子中的任何内容时,应该能够访问帖子页面,但不包括用户的个人资料照片和用户名。有没有更聪明的方法来实现这一点,并保持这样的链接?
代码:
{posts?.map((post) => (
          <Link
            className={classes.link}
            key={post.user.id}
            to={`/posts/${post.id}`}
          >
            <div className={classes.post}>
              <Link to={`/users/${post.user.id}`}>
                <img
                  className={classes.profileImage}
                  src={DefaultLogo}
                  alt="default-profile"
                />
              </Link>
              <article className={classes.postDetails}>
                <Link
                  className={classes.link}
                  to={`/users/${post.user.id}`}
                >
                  <Typography
                    variant="subtitle1"
                    className={`${classes.postTitle} ${classes.content}`}
                  >
                    {post.user.name}
                  </Typography>
                </Link>
                <Typography
                  variant="subtitle1"
                  className={`${classes.postText} ${classes.content}`}
                >
                  {post.body}
                </Typography>
              </article>
            </div>
          </Link>
        ))}
2个回答

3

是的,在一个锚点标签内部放置另一个锚点标签是一种误导性和不好的做法。但考虑到您的要求,您可以使用带有React Router DOM History API的基本按钮。

一个简单的示例:

import {Link, useHistory} from 'react-router-dom'

const App = () => {
  const history = useHistory()


  return (
     <a
      href='/user/1'
     >
       <h2>John doe</h2>
       <div>here are some use information</div>
       {/* Need to prevent the event bubbling */}     
       <Link role='link' to='/users/1/posts'>
           User posts
       </Link> 
     </div>
  )

}

2
请不要这样做。这是错误的重新发明链接方式,只是为了消除React错误。该注释也是不正确的,因为它仅在使用<a>时起作用。永远不要嵌套执行完全不同操作的活动元素,也永远不要使用<div onClick>,因为它不可访问。 - fregante

0
让我们使用一个专门的导航处理函数。我们将用

标签替换那些讨厌的标签,并将onClick事件处理程序连接到

标签上。我们还将利用强大的useNavigate React钩子,它方便地支持在导航过程中向其他组件传递状态。

下面是一个改进后的组件示例:
import { useNavigate } from "react-router-dom";

const NestedLinkSolution = () => {
  const navigate = useNavigate();

  const handleNavigation = (event: React.MouseEvent, childRoute: string) => {
    event.stopPropagation();
    navigate(childRoute);
  };

  return (
      <p
        onClick={(event) => {
          handleNavigation(event, "/parentRoute");
        }}>

         {/* Initial parts of the component */}

        <p
          onClick={(event) => {
            handleNavigation(event, "/childRoute");
          }}>

             Goto Child Route

        </p>

        {/* rest of the component */}

    </p>
  );
};

export default NestedLinkSolution;

通过这种方法,你不仅可以解决问题,还可以为你的代码注入一丝风格。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接