【问题标题】:Warning: validateDOMNesting(…): <a> cannot appear as a descendant of <a>警告:validateDOMNesting(…): <a> 不能作为 <a> 的后代出现
【发布时间】:2021-05-30 06:13:44
【问题描述】:

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

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

代码:

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

【问题讨论】:

    标签: reactjs hyperlink navigation react-router-dom


    【解决方案1】:

    是的,在另一个锚标签中包含锚标签会误导一种糟糕的做事方法。但是根据您的要求,您可以使用带有 react router dom history 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>
      )
    
    }
    

    【讨论】:

      猜你喜欢
      • 2019-09-01
      • 1970-01-01
      • 2019-04-30
      • 2019-02-15
      • 2023-02-11
      • 2019-01-02
      • 1970-01-01
      • 2021-10-25
      • 2020-01-25
      相关资源
      最近更新 更多