简体   繁体   English

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

[英]Warning: validateDOMNesting(...): <a> cannot appear as a descendant of <a>

I'm trying to use react-router with reactstrap with create-react-app .我正在尝试将react-routerreactstrapcreate-react-app一起使用。

In the routing page, I needed to use state for the reactstrap , so I converted the router from a variable to a class, but I get this warning:在路由页面中,我需要为reactstrap使用状态,因此我将路由器从变量转换为类,但我收到以下警告:

 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 this:我需要使用reactstrap设置路由器导航的样式,所以我这样做了:

<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></li> */}
        </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>

{/* just more of the above */}

Other than a couple of <li> coming close to each other at random times, hot reloading not working sometimes, and the warning message I get in the console, nothing bad happens, but when I read about this issue, I found out that I shouldn't do this.除了几个<li>在随机时间彼此靠近,热重新加载有时无法正常工作以及我在控制台中收到警告消息之外,没有任何不好的事情发生,但是当我阅读这个问题时,我发现我不应该这样做。

This is the code which causing the error,这是导致错误的代码,

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

Which is converted to,转换为,

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

So you are getting error,所以你得到错误,

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

To solve this just use one of the follow,要解决此问题,只需使用以下方法之一,

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

OR,或者,

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

Add the as prop (formerly componentClass ) to your original NavLink to keep the styling while also silencing the warning.as道具(以前的componentClass )添加到您的原始NavLink以保持样式同时消除警告。

See react-bootstrap#nav-link-props docs请参阅react-bootstrap#nav-link-props文档

Or View Screenshot查看截图

Original:原来的:

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

New:新的:

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

I would like to suggest an alternate solution which not only solve your problem but give you desired result.我想建议一个替代解决方案,它不仅可以解决您的问题,还可以为您提供所需的结果。 In any case someone else stumbled on this post like I did.无论如何,其他人像我一样偶然发现了这篇文章。

Use Link jsx element offered by react router dom but add classname="nav-link" to it.使用 react router dom 提供的 Link jsx 元素,但添加classname="nav-link"到它。 This will give you styling of the NavLink jsx which react strap is using.这将为您提供反应带正在使用的 NavLink jsx 的样式。

你可以试试这个以避免错误

<NavItem as="li"> <Link>.....

For the people using Gatsby.对于使用 Gatsby 的人。 If you are using a NavBar and a NavDropdown and you want to use a Link inside a NavDropdown.Item you will get an error that:如果您正在使用 NavBar 和 NavDropdown 并且您想在 NavDropdown.Item 中使用链接,您将收到以下错误:

<a> cannot be descendant of <a>

For fixing this error try using as="li" :要修复此错误,请尝试使用 as="li" :

 <NavDropdown title="Services" id="basic-nav-dropdown">
    <NavDropdown.Item as="li">
      <Link to="/Services" className="nav-link">
        Services
      </Link>
    </NavDropdown.Item>
  </NavDropDown>

I had same problem.我有同样的问题。 It is because we can not use link, or a tag inside another like...这是因为我们不能使用链接,或者另一个标签里面的...

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

I wanted to apply className to my a tag in navigation bar.我想将 className 应用于导航栏中的 a 标签。 so i applied className to a tag in component and import that component in navigation bar component所以我将className应用于组件中的标签并将该组件导入导航栏组件

<a className="nav-link" onClick={() => loginWithRedirect()}>
    Login
  </a>

This is how i use this link in navigation template,without any classname这就是我在导航模板中使用此链接的方式,没有任何类名

<LoginButton />

如何修复警告:validateDOMNesting(...):<div> 不能作为孩子出现</div><div id="text_translate"><p>我将用户列表作为道具传递给 UserItem 组件,以迭代用户列表并将它们显示在表上。 列表显示正确,我的渲染返回中没有任何 div,但我仍然收到错误:index.js:1446 Warning: validateDOMNesting(...): cannot appear as a child of.</p><p> 尝试了网上找到的许多解决方案,但没有一个有效</p><p>用户管理代码:</p><pre> import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Spinner from './common/Spinner'; import { getUsers } from '../actions/userActions'; import UserItem from './UserItem'; class UsersManagement extends Component { componentDidMount() { if (.this.props.auth.isAuthenticated) { this.props.history;push('/login'). } this.props;getUsers(), } render() { const { users. loading } = this.props;user; let usersList. if (users === null || loading) { usersList = <Spinner /> } else { if (users.length > 0) { usersList = users.map(user => ( <UserItem key={user._id} user={user} /> )) } else { usersList = <h2>No users</h2> } } return ( <div className="row"> <div className="col-12"> <h1 className="text-center mb-2">Users Management</h1> <button type="button" className="btn btn-success mb-4">New User</button> <table className="table"> <thead> <tr> <th scope="col">Options</th> <th scope="col">Username</th> <th scope="col">Email</th> <th scope="col">Phone Number</th> </tr> </thead> <tbody> {usersList} </tbody> </table> </div> </div> ) } } UsersManagement:propTypes = { getUsers. PropTypes.func,isRequired: auth. PropTypes.object,isRequired: user. PropTypes.object:isRequired } const mapStateToProps = state => ({ auth. state,auth: user. state,user }) export default connect(mapStateToProps; { getUsers })(UsersManagement);</pre><p> 用户项目代码:</p><pre> import React, { Component } from 'react'; import PropTypes from 'prop-types'; class UserItem extends Component { render() { const { user } = this.props; console.log(user); return ( <tr> <th scope="row"> <button type="button" className="btn btn-primary fa-xs mr-1"><i className="fas fa-pencil-alt"></i></button> <button type="button" className="btn btn-danger fa-xs"><i className="far fa-trash-alt"></i></button> </th> <td>{user.username}</td> <td>{user.email}</td> <td>{user.phone}</td> </tr> ) } } UserItem.propTypes = { user: PropTypes.object.isRequired } export default UserItem;</pre><p> 我希望修复警告信息</p></div> - How to fix Warning: validateDOMNesting(...): <div> cannot appear as a child of <tbody>

Gatsby 警告:validateDOMNesting(...):不能作为子项出现<div></div><div id="text_translate"><p>我正在学习通过几个教程构建 Gatsby 站点。 我正在使用 Gatsby 2.13.50(CLI:2.7.14)。 通常,这些教程会教我们构建基本模板。 当我打开开发工具到控制台时,它加载得很好,除了这个警告:</p><pre> Warning: validateDOMNesting(...): <html> cannot appear as a child of <div>.</pre><p> 警告非常非常长。 我将在我的代码之后发布它的 rest。</p><p> 我的 layout.js 基本模板位于 /src/components/layout.js。 它看起来像这样:</p><pre> import React from "react" const Layout = (props) => { return ( <html lang="en"> <head> <Helmet> <meta charSet="utf-8" /> <title>Demo</title> </Helmet> </head> <body> {props.children} </body> </html> ) } export default Layout</pre><p> 它由 /src/pages/index.js 使用,如下所示:</p><pre> import React from 'react' import Layout from '../components/layout' const IndexPage = () => { return ( <Layout> <h1>Demo onle.</h1> <p>Hello. This totally works fine.</p> </Layout> ) } export default IndexPage</pre><p> 如前所述,它有效,除了开发工具控制台中的非常长的警告。</p><p> 我用谷歌搜索了这个,但还没有发现这是怎么发生的以及如何避免它。 我发现有一个<a href="https://www.gatsbyjs.org/docs/custom-html/" rel="nofollow noreferrer">html.js</a>但我不知道这是否是某种默认模板以及我是否应该覆盖它以用作基本模板。 我试过了,但性能很差,所以我认为我错了。</p><p> 当我删除<html>标签时,我得到: Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag.</p><p> 如果我用<div>替换它 它说<body> cannot appear as a child of <div></p><p> 这是很长的警告:</p><pre> Warning: validateDOMNesting(...): <html> cannot appear as a child of <div>. in html (at layout.js:10) in Layout (at chat.js:6) in ChatPage (created by HotExportedChatPage) in AppContainer (created by HotExportedChatPage) in HotExportedChatPage (created by PageRenderer) in PageRenderer (at json-store.js:93) in JSONStore (at root.js:51) in RouteHandler (at root.js:73) in div (created by FocusHandlerImpl) in FocusHandlerImpl (created by Context.Consumer) in FocusHandler (created by RouterImpl) in RouterImpl (created by Context.Consumer) in Location (created by Context.Consumer) in Router (created by EnsureResources) in ScrollContext (at root.js:64) in RouteUpdates (at root.js:63) in EnsureResources (at root.js:61) in LocationHandler (at root.js:119) in LocationProvider (created by Context.Consumer) in Location (at root.js:118) in Root (at root.js:127) in _default (at app.js:65) __stack_frame_overlay_proxy_console__ @ index.js:2177 warningWithoutStack @ react-dom.development.js:507 validateDOMNesting @ react-dom.development.js:8625 createInstance @ react-dom.development.js:8737 completeWork @ react-dom.development.js:16901 completeUnitOfWork @ react-dom.development.js:19143 performUnitOfWork @ react-dom.development.js:19341 workLoop @ react-dom.development.js:19353 renderRoot @ react-dom.development.js:19436 performWorkOnRoot @ react-dom.development.js:20343 performWork @ react-dom.development.js:20255 performSyncWork @ react-dom.development.js:20229 requestWork @ react-dom.development.js:20098 scheduleWork @ react-dom.development.js:19912 enqueueSetState @ react-dom.development.js:11170./node_modules/react/cjs/react.development.js.Component.setState @ react.development.js:335 (anonymous) @ index.js:104 requestAnimationFrame (async) (anonymous) @ index.js:102 Promise.then (async) (anonymous) @ index.js:100 (anonymous) @ history.js:70 navigate @ history.js:69 (anonymous) @ navigation.js:103 Promise.then (async) navigate @ navigation.js:77 window.___navigate @ navigation.js:150 navigate @ index.js:213 onClick @ index.js:184 onClick @ index.js:464 callCallback @ react-dom.development.js:150 invokeGuardedCallbackDev @ react-dom.development.js:200 invokeGuardedCallback @ react-dom.development.js:257 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:271 executeDispatch @ react-dom.development.js:562 executeDispatchesInOrder @ react-dom.development.js:584 executeDispatchesAndRelease @ react-dom.development.js:681 executeDispatchesAndReleaseTopLevel @ react-dom.development.js:689 forEachAccumulated @ react-dom.development.js:663 runEventsInBatch @ react-dom.development.js:817 runExtractedEventsInBatch @ react-dom.development.js:825 handleTopLevel @ react-dom.development.js:4827 batchedUpdates$1 @ react-dom.development.js:20440 batchedUpdates @ react-dom.development.js:2152 dispatchEvent @ react-dom.development.js:4906 (anonymous) @ react-dom.development.js:20491 unstable_runWithPriority @ scheduler.development.js:255 interactiveUpdates$1 @ react-dom.development.js:20490 interactiveUpdates @ react-dom.development.js:2171 dispatchInteractiveEvent @ react-dom.development.js:4883</pre><p> 我应该如何修复此警告?</p></div> - Gatsby Warning: validateDOMNesting(...): <html> cannot appear as a child of <div>

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 警告:validateDOMNesting(...): <form> 不能作为 <form> - Warning: validateDOMNesting(…): <form> cannot appear as a descendant of <form> React --&gt; 警告:validateDOMNesting(...):<p> 不能作为后代出现<p> - React --> Warning: validateDOMNesting(...): <p> cannot appear as a descendant of <p> index.js:1 警告:validateDOMNesting(...):<ul> 不能作为后代出现<p></p></ul> - index.js:1 Warning: validateDOMNesting(...): <ul> cannot appear as a descendant of <p> 如何修复此警告 - 警告:validateDOMNesting(...): <a>cannot appear as a descendant of</a> <a>.</a> <a>下面是我的代码</a> - How do I fix this warning- Warning: validateDOMNesting(…): <a> cannot appear as a descendant of <a>. below is my code 警告:validateDOMNesting(…):<form> 不能通过使用语义-ui-react 模态显示为的后代</form> - Warning: validateDOMNesting(…): <form> cannot appear as a descendant of <form> by using semantic-ui-react modal 警告:validateDOMNesting(…):<div> 不能作为孩子出现<tbody> - Warning: validateDOMNesting(…): <div> cannot appear as a child of <tbody> 如何修复警告:validateDOMNesting(...):<div> 不能作为孩子出现</div><div id="text_translate"><p>我将用户列表作为道具传递给 UserItem 组件,以迭代用户列表并将它们显示在表上。 列表显示正确,我的渲染返回中没有任何 div,但我仍然收到错误:index.js:1446 Warning: validateDOMNesting(...): cannot appear as a child of.</p><p> 尝试了网上找到的许多解决方案,但没有一个有效</p><p>用户管理代码:</p><pre> import React, { Component } from 'react'; import PropTypes from 'prop-types'; import { connect } from 'react-redux'; import Spinner from './common/Spinner'; import { getUsers } from '../actions/userActions'; import UserItem from './UserItem'; class UsersManagement extends Component { componentDidMount() { if (.this.props.auth.isAuthenticated) { this.props.history;push('/login'). } this.props;getUsers(), } render() { const { users. loading } = this.props;user; let usersList. if (users === null || loading) { usersList = <Spinner /> } else { if (users.length > 0) { usersList = users.map(user => ( <UserItem key={user._id} user={user} /> )) } else { usersList = <h2>No users</h2> } } return ( <div className="row"> <div className="col-12"> <h1 className="text-center mb-2">Users Management</h1> <button type="button" className="btn btn-success mb-4">New User</button> <table className="table"> <thead> <tr> <th scope="col">Options</th> <th scope="col">Username</th> <th scope="col">Email</th> <th scope="col">Phone Number</th> </tr> </thead> <tbody> {usersList} </tbody> </table> </div> </div> ) } } UsersManagement:propTypes = { getUsers. PropTypes.func,isRequired: auth. PropTypes.object,isRequired: user. PropTypes.object:isRequired } const mapStateToProps = state => ({ auth. state,auth: user. state,user }) export default connect(mapStateToProps; { getUsers })(UsersManagement);</pre><p> 用户项目代码:</p><pre> import React, { Component } from 'react'; import PropTypes from 'prop-types'; class UserItem extends Component { render() { const { user } = this.props; console.log(user); return ( <tr> <th scope="row"> <button type="button" className="btn btn-primary fa-xs mr-1"><i className="fas fa-pencil-alt"></i></button> <button type="button" className="btn btn-danger fa-xs"><i className="far fa-trash-alt"></i></button> </th> <td>{user.username}</td> <td>{user.email}</td> <td>{user.phone}</td> </tr> ) } } UserItem.propTypes = { user: PropTypes.object.isRequired } export default UserItem;</pre><p> 我希望修复警告信息</p></div> - How to fix Warning: validateDOMNesting(...): <div> cannot appear as a child of <tbody> 反应:警告:validateDOMNesting(...):空白文本节点不能作为子节点出现 - React: Warning: validateDOMNesting(…): Whitespace text nodes cannot appear as a child of <tr> 反应:警告:validateDOMNesting(…):文本节点不能显示为以下子项<tbody> - React: Warning: validateDOMNesting(…): Text nodes cannot appear as a child of <tbody> Gatsby 警告:validateDOMNesting(...):不能作为子项出现<div></div><div id="text_translate"><p>我正在学习通过几个教程构建 Gatsby 站点。 我正在使用 Gatsby 2.13.50(CLI:2.7.14)。 通常,这些教程会教我们构建基本模板。 当我打开开发工具到控制台时,它加载得很好,除了这个警告:</p><pre> Warning: validateDOMNesting(...): <html> cannot appear as a child of <div>.</pre><p> 警告非常非常长。 我将在我的代码之后发布它的 rest。</p><p> 我的 layout.js 基本模板位于 /src/components/layout.js。 它看起来像这样:</p><pre> import React from "react" const Layout = (props) => { return ( <html lang="en"> <head> <Helmet> <meta charSet="utf-8" /> <title>Demo</title> </Helmet> </head> <body> {props.children} </body> </html> ) } export default Layout</pre><p> 它由 /src/pages/index.js 使用,如下所示:</p><pre> import React from 'react' import Layout from '../components/layout' const IndexPage = () => { return ( <Layout> <h1>Demo onle.</h1> <p>Hello. This totally works fine.</p> </Layout> ) } export default IndexPage</pre><p> 如前所述,它有效,除了开发工具控制台中的非常长的警告。</p><p> 我用谷歌搜索了这个,但还没有发现这是怎么发生的以及如何避免它。 我发现有一个<a href="https://www.gatsbyjs.org/docs/custom-html/" rel="nofollow noreferrer">html.js</a>但我不知道这是否是某种默认模板以及我是否应该覆盖它以用作基本模板。 我试过了,但性能很差,所以我认为我错了。</p><p> 当我删除<html>标签时,我得到: Parsing error: Adjacent JSX elements must be wrapped in an enclosing tag.</p><p> 如果我用<div>替换它 它说<body> cannot appear as a child of <div></p><p> 这是很长的警告:</p><pre> Warning: validateDOMNesting(...): <html> cannot appear as a child of <div>. in html (at layout.js:10) in Layout (at chat.js:6) in ChatPage (created by HotExportedChatPage) in AppContainer (created by HotExportedChatPage) in HotExportedChatPage (created by PageRenderer) in PageRenderer (at json-store.js:93) in JSONStore (at root.js:51) in RouteHandler (at root.js:73) in div (created by FocusHandlerImpl) in FocusHandlerImpl (created by Context.Consumer) in FocusHandler (created by RouterImpl) in RouterImpl (created by Context.Consumer) in Location (created by Context.Consumer) in Router (created by EnsureResources) in ScrollContext (at root.js:64) in RouteUpdates (at root.js:63) in EnsureResources (at root.js:61) in LocationHandler (at root.js:119) in LocationProvider (created by Context.Consumer) in Location (at root.js:118) in Root (at root.js:127) in _default (at app.js:65) __stack_frame_overlay_proxy_console__ @ index.js:2177 warningWithoutStack @ react-dom.development.js:507 validateDOMNesting @ react-dom.development.js:8625 createInstance @ react-dom.development.js:8737 completeWork @ react-dom.development.js:16901 completeUnitOfWork @ react-dom.development.js:19143 performUnitOfWork @ react-dom.development.js:19341 workLoop @ react-dom.development.js:19353 renderRoot @ react-dom.development.js:19436 performWorkOnRoot @ react-dom.development.js:20343 performWork @ react-dom.development.js:20255 performSyncWork @ react-dom.development.js:20229 requestWork @ react-dom.development.js:20098 scheduleWork @ react-dom.development.js:19912 enqueueSetState @ react-dom.development.js:11170./node_modules/react/cjs/react.development.js.Component.setState @ react.development.js:335 (anonymous) @ index.js:104 requestAnimationFrame (async) (anonymous) @ index.js:102 Promise.then (async) (anonymous) @ index.js:100 (anonymous) @ history.js:70 navigate @ history.js:69 (anonymous) @ navigation.js:103 Promise.then (async) navigate @ navigation.js:77 window.___navigate @ navigation.js:150 navigate @ index.js:213 onClick @ index.js:184 onClick @ index.js:464 callCallback @ react-dom.development.js:150 invokeGuardedCallbackDev @ react-dom.development.js:200 invokeGuardedCallback @ react-dom.development.js:257 invokeGuardedCallbackAndCatchFirstError @ react-dom.development.js:271 executeDispatch @ react-dom.development.js:562 executeDispatchesInOrder @ react-dom.development.js:584 executeDispatchesAndRelease @ react-dom.development.js:681 executeDispatchesAndReleaseTopLevel @ react-dom.development.js:689 forEachAccumulated @ react-dom.development.js:663 runEventsInBatch @ react-dom.development.js:817 runExtractedEventsInBatch @ react-dom.development.js:825 handleTopLevel @ react-dom.development.js:4827 batchedUpdates$1 @ react-dom.development.js:20440 batchedUpdates @ react-dom.development.js:2152 dispatchEvent @ react-dom.development.js:4906 (anonymous) @ react-dom.development.js:20491 unstable_runWithPriority @ scheduler.development.js:255 interactiveUpdates$1 @ react-dom.development.js:20490 interactiveUpdates @ react-dom.development.js:2171 dispatchInteractiveEvent @ react-dom.development.js:4883</pre><p> 我应该如何修复此警告?</p></div> - Gatsby Warning: validateDOMNesting(...): <html> cannot appear as a child of <div>
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM