作为reactJS的初学者,我想知道当我路由到子组件URL时如何隐藏父组件
假设一个场景:
用户位于“ / house”,如下所示:
<Route path="/house" component={House} />
当用户单击房屋网格时,他导航到“ / house / flat /:flatID”。内部房屋组件
<Route
path={`${this.props.match.url}/flat/:flatId`}
render={() => <div>Each Flat details</div>}
/>
所以我想要的是当用户导航到“ / house / flat:FlatId”时仅显示平面组件。请给我建议任何有帮助的东西!文章的任何链接,以便我可以学习并实现这种功能。
代码:
App.js
<Switch>
<Route exact path="/" component={Home} />
<Route exact path="/account" component={Account} />
<Route path="/gharjagga" component={GharJagga} />
</Switch>
House.js
onGharGridClick= id => {
<Redirect to={`${this.props.match.url}/flat/${id}`} />;
};
return (
<Route
path={`${this.props.match.url}/flat/:fkatId`}
render={() => <div>Ghar Each</div>}
/>
);
答案 0 :(得分:4)
您可以通过不同的方式实现它
<Switch>
<Route path="/account" component={Account} />
<Route path="/house/flat/:flatId" component={FlatComponent}/>
<Route path="/house" component={House} />
<Route path="/" component={Home} />
</Switch>
注意:不要使用exact
,而是根据优先级对路由进行排序,如果输入的路由中有任何错别字,这将使该路由重定向到下一个匹配的路由
// ROutes
<Switch>
<Route path="/account" component={Account} />
<Route path="/house" component={House} />
<Route path="/" component={Home} />
</Switch>
// House component
class House extends React. Components {
render() {
return (
<Switch>
<Route path="/house/flat/:flatId" render={() => <div>Each Flat details</div>} />}/>
<Route path="/house" component={HouseGridComponent} />
</Switch>
)
}
}
flatId
并隐藏元素,在House组件中可以检查this.props.match.params.flatId
,如果设置了flatId
,则可以隐藏该House组件。 / li>
// House Component
class House extends React. Components {
render() {
return (
<div>
{
!this.props.match.params.flatId?
<h1>House Component</h1>:
null
}
<Route path={`${this.props.match.url}/flat/:flatId`} render={() => <div>Each Flat details</div>} />
</div>
)
}
}
答案 1 :(得分:2)
解决方案是将"/house/flat/:flatId"
提升到与"/house"
相同的水平。
<Switch>
<Route exact path="/" component={Home} />
<Route path="/account" component={Account} />
<Route path="/house/flat/:flatId" render={() => <div>Each Flat details</div>}/>
<Route path="/house" component={House} />
</Switch>