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

Warning: validateDOMNesting(…): <a> cannot appear as a descendant of <a>

我正在使用 React 路由器 dom Link 组件。它基本上是推特的主页。我希望能够在一个 div 组件中包含两种类型的 Link。一个是 Link 转到用户的个人资料,另一个是 post。我目前收到警告,暂时找不到解决方案。以下是截图作为参考:

我理解这里的问题,我的 post Link 是父元素,我在其中添加了两个用户 Link 组件,因为用户应该能够访问post 页面,当他单击 post 中除了用户的个人资料照片和用户名以外的任何内容时。有没有更聪明的方法来实现这一目标并保持这样的链接?

代码:

{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>
        ))}

是的,在另一个锚标签内放置锚标签会误导一种糟糕的做事方法。但是根据您的要求,您可以使用带有反应路由器 dom 历史 api.

的基本按钮

一个简单的例子:

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

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

  // dont forget the [role='link'] or it won't allow feature like open in new tab. Hence, it will behave as <a>

  return (
     <div 
       role='link' 
       onClick={
         () => history.push('/user/1')
       }
     >
       <h2>John doe</h2>
       <div>here are some use information</div>     
       <Link role='link' to='/users/1/posts'>
           User posts
       </Link> 
     </div>
  )

}