Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
2.4k views
in Technique[技术] by (71.8m points)

reactjs - validateDOMNesting warning React

I have a React component that is clickable as a whole, but also contains buttons inside.

So something like

<Link to={'/path1'}>
  ...
  <Link to={'path2'} />
  ...
</Link> 

This is the behaviour I want, but I get this warning:

Warning: validateDOMNesting(...): <a> cannot appear as a descendant of <a>. See SearchResult > Link > a > ... > Link > a.

How seriously should I take this and what would be the workaround?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Nesting anchor tags (which is what <Link /> transpiles to) is forbidden in HTML. Even if you get the desired result, it is only because your browser is clever and has its own work-arounds. However, that behavior cannot be guaranteed across all browsers and platforms.

How seriously should I take this?

As per the above, I'd say quite seriously.

What would be the workaround?

The following isn't a workaround, but what I consider to be the "proper" implementation.

I'd programatically implement the navigation for the wrapping element and use the <Link /> for the buttons. So something like:

navigate = () => {
  //push "path1" to history
}

render() {
  return(
    <div onClick={this.navigate}>
      <Link to="path2">Some button</Link>
      <Link to="path3">Some button</Link>
    </div>
  );
}

For more info about programatically navigating in React Router see one of the links below:

  • For React Router v1-v3: Link
  • For React Router v4: Link

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...