我在尝试将ui-fabric Nav组件与react-router-dom v4+配合使用时遇到了困难。我的解决方案“可行”,但整个页面重新渲染,而不仅仅是NavSelection组件。经过一些研究,我意识到需要在某个地方添加e.preventDefault(),但我无法确定在哪里添加它。
主页面:
导航栏:
任何帮助都将不胜感激。
编辑:我已经尝试将它放在componentDidMount里面,就像这样:
主页面:
export const Home = () => {
return (
<div className="ms-Grid-row">
<div className="ms-Grid-col ms-u-sm6 ms-u-md4 ms-u-lg2">
<Navbar />
</div>
<div className="ms-Grid-col ms-u-sm6 ms-u-md8 ms-u-lg10">
<NavSelection />
</div>
</div>
);
}
导航栏:
const navGroups = [
{
links: [
{ name: 'Name1', url: '/Name1', key: '#Name1' },
{ name: 'Name2', url: '/Name2', key: '#Name2' }
]
}
];
export class Navbar extends React.Component<any, any> {
constructor(props: INavProps) {
super(props);
this.state = {
selectedNavKey: '#Name1'
};
}
public componentDidMount() {
window.addEventListener('hashchange', (e) => {
this.setState({ selectedNavKey: document.location.hash || '#' });
});
}
public render(): JSX.Element {
const { selectedNavKey } = this.state;
return (
<Nav
selectedKey={selectedNavKey}
groups={navGroups}
/>
);
}
}
导航选择:
export const NavSelection = () => {
return (
<div>
<Route path="/Name1" component={Component1} />
<Route path="/Name2" component={Component2} />
</div>
);
}
任何帮助都将不胜感激。
编辑:我已经尝试将它放在componentDidMount里面,就像这样:
public componentDidMount() {
window.addEventListener('hashchange', (e) => {
e.preventDefault();
this.setState({ selectedNavKey: document.location.hash || '#' });
});
}
那不起作用。