javascript - 如何添加外部链接到 react-bootstrap Navbar?

标签 javascript html reactjs twitter-bootstrap-3 hyperlink

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

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

这会产生以下警告:

Warning: validateDOMNesting(...): cannot appear as a descendant of . See App > NavItem > SafeAnchor > a > ... > a.

我知道警告来自 NavItem 的事实已经生成一个 <a>元素。

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

最简单的 hack-around 似乎取代了 <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

Loose text and links can be wraped in the convenience components: Navbar.Link and 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/

相关文章:

javascript - 在 for 循环内动态创建变量,Javascript

javascript - React-i18next,从 props 添加资源

reactjs - Foundation,React 在单击切换按钮时抛出 "el.data(...).split is not a function"

javascript - 如何更改 D3.js 中点的颜色以反射(reflect) y 尺度上的数据?

javascript - Kendo UI 可见绑定(bind)不起作用

html - 如何使元素超出其父元素的范围?

javascript - <li> 元素如何在没有 CSS position 或 margin-top 的情况下上下移动?

javascript - 删除jquery中的空双引号

javascript - React Draft 所见即所得不会加载 css 样式

javascript - meteor /铁路由器 : how to wait on data which depends on other data