Bir navigasyon cihazındaki React-Bootstrap bağlantı öğesi


86

React-router ve react-bootstrap kullanarak bazı şekillendirme sorunları yaşıyorum. aşağıda kodun bir parçası

import { Route, RouteHandler, Link } from 'react-router';
import AuthService from '../services/AuthService'
import { Button, Nav, Navbar, NavDropdown, MenuItem, NavItem } from 'react-bootstrap';

    <Nav pullRight>
      <NavItem eventKey={1}>
        <Link to="home">Home</Link>
      </NavItem>
      <NavItem eventKey={2}>
        <Link to="book">Book Inv</Link>
      </NavItem>
      <NavDropdown eventKey={3} title="Authorization" id="basic-nav-dropdown">
        <MenuItem eventKey="3.1">
          <a href="" onClick={this.logout}>Logout</a>
        </MenuItem>          
      </NavDropdown>  
    </Nav>

Oluşturulduğu zaman böyle görünüyor.

görüntü açıklamasını buraya girin

Buna <Link></Link>neden olduğunu biliyorum ama nedenini bilmiyorum? Bunun sıralı olmasını isterim.

Yanıtlar:


5

İçine çapa koymamalısın NavItem. Bunu yaptığınızda konsolda bir uyarı göreceksiniz:

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

Bunun nedeni, ne zaman NavItembir çapa (doğrudan çocuğu) haline getirildiğinde NavItemzaten orada olmasıdır.

Yukarıdaki uyarı nedeniyle tepki, stil sorununa neden olan iki çapayı kardeş olarak ele almak zorunda kalacak.


4
Bir bağlantı kapsayıcı kullanmak zorunda kaldım .
— chad schmidt

3
Lütfen bir örnek verebilir misiniz?
— Paschalidis Christos

5
Sorunu kabul edilen bir cevapla değil, ikinci cevapla çözülen tek kişi ben miyim?
— Ejaz Karim

1
@chadschmidt lütfen kabul edilen cevabı stackoverflow.com/a/36933127/1826429
— Goldy

249

Kullanılması LinkContainer gelen tepki-yönlendirici-bootstrap gitmek yoludur. Aşağıdaki kod çalışmalıdır.

import { Route, RouteHandler, Link } from 'react-router';
import AuthService from '../services/AuthService'
import { Button, Nav, Navbar, NavDropdown, MenuItem, NavItem } from 'react-bootstrap';
import { LinkContainer } from 'react-router-bootstrap';

/// In the render() method
<Nav pullRight>
  <LinkContainer to="/home">
    <NavItem eventKey={1}>Home</NavItem>
  </LinkContainer>
  <LinkContainer to="/book">
    <NavItem eventKey={2}>Book Inv</NavItem>
  </LinkContainer>
  <NavDropdown eventKey={3} title="Authorization" id="basic-nav-dropdown">
    <LinkContainer to="/logout">
      <MenuItem eventKey={3.1}>Logout</MenuItem>    
    </LinkContainer>      
  </NavDropdown>  
</Nav>

Bu konuyu araştırırken bu çoğunlukla gelecekteki benlik için bir nottur. Umarım cevaptan bir başkası yararlanabilir.



4
activeClassName'i değiştirmeye ne dersiniz?
— Anyul Rivas

Bunun çalışmasını sağlayamazsanız, yolunuzun React Router'a dahil edildiğinden emin olun.
— Anant Simran Singh

8
Bu, "etkin" stili NavItems'e uygulayamaz.
— Daniel Arant

1
Aşağıda, active / activeKey çalışmıyorken sorunu çözen bir cevap ekledim. React-bootstrap v_1.0 beta ile de çalışır! (Normal sürümle kullanmak için, Nav.Item fro NavItem vb. Çıkarın)
— Young Scooter

52

2020 güncel:react-boostrap: 1.0.0-beta.16 ve ile test edildireact-router-dom: 5.1.2

2019 upd: react-bootstrap v4 (şu anda 1.0.0-beta.5 kullanıyor) ve react-router-dom v4 (4.3.1) ile çalışanlar için Nav.Link'ten "as" prop kullanın, işte dolu misal:

import { Link, NavLink } from 'react-router-dom'
import { Navbar, Nav } from 'react-bootstrap'

<Navbar>
  {/* "Link" in brand component since just redirect is needed */}
  <Navbar.Brand as={Link} to='/'>Brand link</Navbar.Brand>
  <Nav>
    {/* "NavLink" here since "active" class styling is needed */}
    <Nav.Link as={NavLink} to='/' exact>Home</Nav.Link>
    <Nav.Link as={NavLink} to='/another'>Another</Nav.Link>
    <Nav.Link as={NavLink} to='/onemore'>One More</Nav.Link>
  </Nav>
</Navbar>

İşte çalışma örneği: https://codesandbox.io/s/3qm35w97kq


az önce denedim, sadece 'as = {NavLink}' ile çalışmıyor.
— lannyboy

1
Bu, react-bootstrap 1 ile react router v5'te çalışır ve 16.8'e tepki verir
— proc

Boostrap vue'nun basitçe "to" parametresini uyguladığı ve yönettiği Vue.js'den geliyorum ve bunu çok daha kolay buluyorum. Yine de bahşiş için teşekkürler, çok yardımcı oldu!
— egdavid

1
Bu çözüm desteklediği için LinkContainer, yerine bu çözümü kullanın . react-router-bootstrapactiveClassName
— takasoft

Teşekkür ederim @Alexey. LinkContainer'ı çalıştırmaya çalışırken saatler harcadıktan sonra bu yanıtı buldum.
— David Easley

31

React-bootstrap kullanmayı denediniz componentClassmi?

import { Link } from 'react-router';
// ...
<Nav pullRight>
  <NavItem componentClass={Link} href="https://stackoverflow.com/" to="/">Home</NavItem>
  <NavItem componentClass={Link} href="https://stackoverflow.com/book" to="/book">Book Inv</NavItem>
</Nav>

1
Bu iyi çalışıyor! Hiçbir şekillendirme sorunu yok ve geçersiz kılma gerektiren diğer yanıtlardan çok daha basit, sadece href / to'nun tekrarını önlemek için bir HoC ile de geçersiz kılabilirsiniz.
— Tim Lind

1
Bu çok temiz, şu anda harici bir bağlantı için "boş hedef" ile kullandım ve çok iyi çalışıyor. Teşekkürler
— Saulo Gomes

1
Bu, başka bir paket eklemeye gerek kalmadan daha iyidir.
— sbk201

2
1.0.0-beta.5'e yükseltildi. ComponentClass için desteği kaldırmış gibi görünüyorlar :(
— Nate-Bit Int

12

LinkContainerReact-router-bootstrap'ı kullanmaktan kaçınabilirsiniz . Ancak componentClassolmaya devam etmektedir assonraki sürümünde. Dolayısıyla, son sürüm (v1.0.0-beta) için aşağıdaki parçacığı kullanabilirsiniz:

<Nav>
    <Nav.Link as={Link} to="/home" >
        Home
    </Nav.Link>
    <Nav.Link as={Link} to="/book" >
        Book Inv
    </Nav.Link>
    <NavDropdown title="Authorization" id="basic-nav-dropdown">
        <NavDropdown.Item onClick={props.logout}>
            Logout
        </NavDropdown.Item>
    </NavDropdown>
</Nav>

5

İşte react-router 4 ile kullanım için bir çözüm:

import * as React from 'react';

import { MenuItem as OriginalMenuItem, NavItem as OriginalNavItem } from 'react-bootstrap';

export const MenuItem = ({ href, ...props }, { router }) => (
  <OriginalMenuItem onClick={e => {e.preventDefault();router.transitionTo(href)}} href={href} {...props}/>
);

MenuItem.contextTypes = {
  router: React.PropTypes.any
};

export const NavItem = ({ href, ...props }, { router }) => (
  <OriginalNavItem onClick={e => {e.preventDefault();router.transitionTo(href)}} href={href} {...props}/>
);

NavItem.contextTypes = {
  router: React.PropTypes.any
};

Bunun yerine kullanmanın router.transitionTo(href)kullanımınırouter.history.push(href)
— Devasatyam

3

IndexLinkContainer, iç NavItem'in mevcut seçime göre hangisinin etkin olduğunu vurgulamasını istiyorsanız LinkContainer'dan daha iyi bir seçenektir . Manuel seçim işleyicisine gerek yoktur

import { IndexLinkContainer } from 'react-router-bootstrap';
....

//Inside render
<Nav bsStyle="tabs" >
  <IndexLinkContainer to={`${this.props.match.url}`}>
    <NavItem >Tab 1</NavItem>
  </IndexLinkContainer>
  <IndexLinkContainer to={`${this.props.match.url}/tab-2`}>
    <NavItem >Tab 2</NavItem>
  </IndexLinkContainer>
  <IndexLinkContainer to={`${this.props.match.url}/tab-3`}>
    <NavItem >Tab 3</NavItem>
  </IndexLinkContainer>
</Nav>

Sekme kullanmıyorum ancak gezinme çubuğumdaki bağlantının etkin olarak vurgulanmasını istiyorum. IndexLinkContainer'ı kullanmayı denedim ve belirttiğiniz gibi çalışmıyor. Doğrudan bir rotaya gidersem, doğru olanı vurgular, ancak yalnızca bağlantıları tıklarsam değil.
— Thomas Le

btw sadece merak ediyorum nasıl buldunuz IndexLinkContainer? belgelerde hiçbir yerde bulamadım ...
— Thiem Nguyen

@ThomasLe Bileşen ve PureComponent kullanımınızı kontrol edin. Bileşen
— FrozenKiwi

2

Geçmişi kullanabilirsiniz , sadece bileşeni yönlendirici ile oluşturduğunuzdan emin olun :

App.js'de:

// other imports
import {withRouter} from 'react-router';

const NavigationWithRouter = withRouter(Navigation);

//in render()
    <NavigationWithRouter />

Navigation.js'de:

//same code as you used before, just make an onClick event for the NavItems instead of using Link

<Nav pullRight>
  <NavItem eventKey={1} onClick={ e => this.props.history.push("/home") } >
    Home
  </NavItem>
  <NavItem eventKey={2} onClick={ e => this.props.history.push("/book") } >
    Book Inv
  </NavItem>
</Nav>

0

React-bootstrap v_1.0 beta sürümünde "activeKey" prop ile işlevsellik eklemek için şu biçimi kullanın:

<Nav activeKey={//evenKey you want active}>
    <Nav.Item>
        <LinkContainer to={"/home"} >
            <Nav.Link eventKey={//put key here}>
                {x.title}
            </Nav.Link>
        </LinkContainer>
    </Nav.Item>
    //other tabs go here
</Nav>
Sitemizi kullandığınızda şunları okuyup anladığınızı kabul etmiş olursunuz: Çerez Politikası ve Gizlilik Politikası.
Licensed under cc by-sa 3.0 with attribution required.