【发布时间】:2017-09-07 08:47:59
【问题描述】:
我正在使用 React 路由器 v4 来渲染路由。我有一个简单的路由组件,它路由到项目列表和编辑现有/添加新项目。这是一个使用引导程序构建的简单选项卡组件。我想将选项卡组件的标题更改为Add new 或Edit existing,具体取决于路由是否具有 id 属性。
理想情况下,我希望避免需要创建额外的组件,因为这不会增强代码的可读性。
public render() {
const { match, location } = this.props;
const customers = cx({ active: !location.pathname.includes("AddEdit") });
const editItem = cx({ active: location.pathname.includes("AddEdit") });
const hasIdParam = {/* Some way to read match params to get the id */};
return <div className='nav-component-container'>
<nav>
<ul>
<li role="presentation" className={items}><NavLink to={`${match.url}/All`} activeClassName='active'>Items</NavLink></li>
<li role="presentation" className={editItem}>
<NavLink to={`${match.url}/AddEdit`} activeClassName='active'>
{/* I'd like this to say either new item or edit existing based on whether the current route has an id parameter or not */}
</NavLink>
</li>
</ul>
</nav>
<Switch>
<Route path={`${match.url}/All`} component={Customers} {...this.props}></Route>
<Route path={`${match.url}/AddEdit/:id?`} component={Item}></Route>
</Switch>
</div>;
}
有各种 hack - 其中最好的似乎是阅读 location.pathname 属性并使用它来确定它是编辑还是添加新的 - 这已经足够了,但我不禁觉得我错过了一些东西在
【问题讨论】:
标签: reactjs react-router react-router-dom