这是我简单的导航栏。 Codepen here

<Navbar inverse collapseOnSelect>
  <Navbar.Collapse>
    <Nav>
      <NavItem eventKey={1}>
        <a href="http://example.com/">
          Example
        </a>
      </NavItem>
    </Nav>
  </Navbar.Collapse>
</Navbar>


生成以下警告:


  警告:validateDOMNesting(...):不能作为的后代出现。请参阅应用程序>导航项>安全锚> a> ...> a。


我理解警告来自于NavItem已经生成<a>元素的事实。

寻找SafeAnchor + React时,我只能找到this seemingly unrelated NPM package

最简单的破解方法似乎是将<a>替换为自定义的点击处理<span>

openLink(href) {
  event.preventDefault();
  window.open(href);
}

...

<span onClick={this.openLink.bind(this, "http://example.com/"}>
  Sandbox
</span>


不确定是否有一个不太复杂的解决方案,但不是很复杂吗?

最佳答案

您可以使用Navbar.LinkNavbar.Text将文本链接和非导航链接添加到Navbar


  Text and Non-nav links
  
  宽松的文本和链接可以包装在便利组件中:Navbar.Link和Navbar.Text


-- JSFiddle Example --

const { Accordion, Panel, Button, Modal, Form, FormGroup,
       FormControl, ControlLabel, Navbar, Nav, NavItem,
       NavDropdown, MenuItem, Jumbotron
      } = ReactBootstrap;

class App extends React.Component {
  render() {
    return <Navbar inverse collapseOnSelect>
      <Navbar.Header>
        <Navbar.Brand>
          <a href="#">Brand</a>
        </Navbar.Brand>
        <Navbar.Toggle />
      </Navbar.Header>
      <Navbar.Collapse>
        <Nav>
          <NavItem eventKey={1} href="#">Link</NavItem>
        </Nav>
        <Navbar.Text>
          <Navbar.Link href="https://google.com" target="_blank">External Link</Navbar.Link>
        </Navbar.Text>
      </Navbar.Collapse>
    </Navbar>;
  }
}

ReactDOM.render(
  <App/>,
  document.getElementById('app')
);

关于javascript - 如何添加外部链接到react-bootstrap Navbar?,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/41074184/

10-12 12:50
查看更多