警告:validateDOMNesting(...):<a> cannot appear as a descendant of </a> <a>

时间:2019-04-11 05:40:47

标签: reactjs react-router create-react-app reactstrap

I'm trying to use react-router with reactstrap in a create-reat-app .In the routing page i needed to use state for the reactstrap so i converted the router from a variable to a class.I get this warning : Warning: validateDOMNesting(...): <a> cannot appear as a descendant of <a>. i don't know what to do ?, i needed to style the router navigation using reactstrap so i did what you see below .

This didn't work for so many reasons :

<NavLink componentClass={Link} href="/contact" to="/contact" active={location.pathname === '/contact'}>anywords</NavLink>
<Navbar  dark id="RouterNavbar" expand="md">
          <NavbarBrand id="NavBrand"href="#x"><ul>(a bunch of li not relevant)</ul></NavbarBrand>
<NavbarToggler id="NavBarToggler"  onClick={this.toggle1.bind(this)}  />
          <Collapse  isOpen={this.state.isOpen1}  navbar>
            <Nav   className="ml-auto"  navbar>
            <NavItem>
                <NavLink href="#x"><Link id="RouterNavLink" style={None} to="/contact">anywords</Link></NavLink>
              </NavItem>
(then just more of the above)

other than a couple of li coming close to each other at random times and me having to refresh the page sometimes instead of the normal behaviour (auto refresh ) and the warning message i get in the console ,nothin bad happens but when i read about this issue i found out that i shouldn't do it.

3 个答案:

答案 0 :(得分:1)

这是导致错误的代码,

<NavLink href="#x"><Link id="RouterNavLink" style={None} to="/contact">anywords</Link></NavLink>

转换为的

<a><a></a></a>

所以您遇到了错误,

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

要解决此问题,请使用以下任一方法,

<NavLink id="RouterNavLink" style={None} to="/contact">anywords</NavLink>

OR

<Link id="RouterNavLink" style={None} to="/contact">anywords</Link>

答案 1 :(得分:0)

as道具(以前为componentClass)添加到原始NavLink中,以在保持样式的同时还消除警告。 https://react-bootstrap.netlify.com/components/navs/#nav-link-props

View Screenshot

原文:

<NavLink href="#x"><Link id="RouterNavLink" style={None} to="/contact">anywords</Link></NavLink>

新功能:

<Nav.Link as={Link} to="/contact">anywords</Nav.Link>

答案 2 :(得分:0)

我想建议一个替代解决方案,它不仅可以解决您的问题,还可以为您提供所需的结果。无论如何,有人像我一样偶然发现了这篇文章。

使用由 react router dom 提供的 Link jsx 元素,但添加 classname="nav-link" 到它。这将为您提供反应带正在使用的 NavLink jsx 的样式。