我确定之前有人问过,我找不到答案。当你点击reactstrap中的Nav
时,你如何让NavLink
菜单关闭?或者这仍在开发中?
Reactstrap在状态中有一个isOpen
参数,所以你需要将它设置为false
constructor(props) {
super(props);
this.closeNavbar = this.closeNavbar.bind(this);
this.state = {
isOpen: false
};
}
closeNavbar() {
this.setState({
isOpen: false
});
}
// and in Link or a element add onClick handler like this
<Link to="/" onClick={closeNavbar}>Home</Link>
这是我使用的代码:
import React, { Component } from 'react';
import { Link } from 'react-router-dom';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import library from './FontAwesomeLibrary';
import logo from '../../assets/images/logo.svg';
import {
Collapse,
Navbar,
NavbarToggler,
Nav,
NavItem } from 'reactstrap';
class Topbar extends Component {
constructor(props) {
super(props);
this.toggle = this.toggle.bind(this);
this.closeNavbar = this.closeNavbar.bind(this);
this.handleClickOutside = this.handleClickOutside.bind(this);
this.state = {
isOpen: false,
};
}
componentWillMount() {
document.addEventListener('mousedown', this.handleClickOutside);
}
componentWillUnmount() {
document.removeEventListener('mousedown', this.handleClickOutside);
}
toggle() {
this.setState({
isOpen: !this.state.isOpen
});
}
closeNavbar() {
this.setState({
isOpen: false
});
}
handleClickOutside(event) {
const t = event.target;
if (this.state.isOpen && !t.classList.contains('navbar-toggler')) {
this.closeNavbar();
}
}
render() {
return (
<div className="topbar">
<section className="container">
<Navbar color="light" className="header" expand="md">
<Link className="locoLink" to="/"><img src={logo} className="logo" alt="logo" /></Link>
<Link to="/" className="logoCompany">Redux Blog</Link>
<NavbarToggler onClick={this.toggle}>
<FontAwesomeIcon icon={this.state.isOpen ? "times" : "bars"}/>
</NavbarToggler>
<Collapse isOpen={this.state.isOpen} navbar>
<Nav className="ml-auto routes" navbar>
<NavItem>
<Link to="/" onClick={this.closeNavbar}>Posts</Link>
</NavItem>
<NavItem>
<Link to="/posts/new" onClick={this.closeNavbar}>New Post</Link>
</NavItem>
</Nav>
</Collapse>
</Navbar>
</section>
</div>
);
}
}
export default Topbar;
它还处理外部点击。
字体真棒图书馆
import { library } from '@fortawesome/fontawesome-svg-core';
import { faCoffee } from '@fortawesome/free-solid-svg-icons';
import { faMugHot } from '@fortawesome/free-solid-svg-icons';
import { faTimes } from '@fortawesome/free-solid-svg-icons';
import { faBars } from '@fortawesome/free-solid-svg-icons';
import { faChevronUp } from '@fortawesome/free-solid-svg-icons';
library.add(faCoffee);
library.add(faMugHot);
library.add(faTimes);
library.add(faBars);
library.add(faChevronUp);
export default library;
我根据https://fontawesome.com/how-to-use/on-the-web/using-with/react创建了FontAwesomeLibrary
这是路由问题。在普通网页上,引导导航中的链接会导致新页面加载,导航现在已关闭。由于反应不会重新加载页面导航保持打开状态。为了解决这个问题,你需要在nav中的每个<Link>
元素中添加以下内容:onClick={this.toggleNavbar}
。