嗨,我有一个带有Tabs的react应用,我正在尝试为我的应用添加路由。 基本上,我希望每个标签将我重定向到不同的网址。
我的<tabs>
组件非常简单,它由多个<Tab>
组件组成。
每个标签只是一个<il>
标签,并带有传递点击功能的道具,并且isActive状态(对于所有标签都是false)接受活动标签。
还有一个主要的Div,其中包含活动的Tab内容组件。
所以我尝试将我的Tab组件包装在Link中
然后将我的div活动标签内容包装在<Route path={}> ...
中
并将我的整个应用包装在<BrowserRouter>
这部分起作用,当我单击其他选项卡时,浏览器中的url更改并且新选项卡已加载。 但是我有两个问题: 1.如果刷新页面,则页面进入根主页。 2.如果我在标签内有一个标签,我希望我的路径是我以前的路径的汇总,并且不能动态工作。
标签:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
class Tab extends Component {
static propTypes = {
activeTab: PropTypes.string.isRequired,
label: PropTypes.string.isRequired,
onClick: PropTypes.func.isRequired,
};
onClick = () => {
const { label, onClick } = this.props;
onClick(label);
};
render() {
const {
onClick,
props: {
activeTab,
label,
},
} = this;
let className = 'tab-list-item';
if (activeTab === label) {
className += ' tab-list-active';
}
return (
<li
className={className}
onClick={onClick}
>
{label}
</li>
);
}
}
export default Tab;
标签:
import React, { Component } from 'react';
import PropTypes from 'prop-types';
import {Link, Route} from 'react-router-dom';
import Tab from './Tab';
class Tabs extends Component {
static propTypes = {
children: PropTypes.instanceOf(Array).isRequired,
};
constructor(props) {
super(props);
this.state = {
activeTab: this.props.children[0].props.label,
tabLink: '',
};
}
componentDidMount() {
const { path } = this.props.match;
console.log('Tabs did mount, path is:' + path);
}
onClickTabItem = (tab) => {
this.setState({ activeTab: tab });
};
render() {
const {
onClickTabItem,
props: {
children,
},
state: {
activeTab,
}
} = this;
return (
<div className="tabs">
<ol className="tab-list">
{children.map((child) => {
const { label } = child.props;
var link = label === 'mainPage' ? '' : label.replace(/ /g, '-');
return (
<Link to={'/' + link}>
<Tab
activeTab={activeTab}
key={label}
label={label}
onClick={onClickTabItem}
/>
</Link>
);
})}
</ol>
<Route path={'/' + (activeTab === 'mainPage' ? '' : activeTab.replace(/ /g, '-'))} render={props => (
<React.Fragment>
<div className="tab-content">
{children.map((child) => {
if (child.props.label !== activeTab) return undefined;
return child.props.children;
})}
</div>
</React.Fragment>
)}/>
</div>
);
}
}
export default Tabs;
主应用程序:
<Router>
<Provider store={store}>
<Header/>
<Tabs>
<div label="mainPage" >
<mainPageView>
</div>
<div label="inner view">
<Tabs>
<div label="inner view 1">
<view 1 selectedOption={selectedOption}/>
</div>
<div label="inner view 2">
<view 2 selectedOption={selectedOption}/>
</div>
</Tabs>
</div>
</Tabs>
</Provider>
</Router>