我正在嘗試在登錄頁面上設定一個透明的導航欄,但我不希望它在其他頁面上是透明的。有沒有辦法做到這一點,或者我應該嘗試另一種方法?
render() {
return (
<>
{
Route.path === '/' ? <Header transparent={this.state.transparent} /> : <Header />
}
<Switch>
<Route path='/' exact component={Home} />
<Route path='/aboutus' component={AboutUs} />
<Route path='/shop' component={Shop} />
</Switch>
<Footer />
</>
);
}
我想做這樣的事情或者當路徑不同時洗掉透明屬性的方法
這里是狀態
constructor(props) {
super(props)
this.state = {
transparent: true,
}
this.listener = null}
其余的代碼是
componentDidMount() {
this.listener = document.addEventListener('scroll', e => {
let scrolled = document.scrollingElement.scrollTop;
if (scrolled >= 150) {
if (this.state.transparent !== false) {
this.setState({ transparent: false});
}
} else {
if (this.state.transparent !== true) {
this.setState({ transparent: true});
}
}
});
}
componentDidUpdate() {
document.removeEventListener("scroll", this.listener);
}
伙計們,我能在這里做什么?
uj5u.com熱心網友回復:
要確定當前路徑使用useLocation().pathname鉤子。為此,您需要 6.x 版的 react-router-dom(即使在 5.x 上也不知道是否有效),然后代碼應如下所示:
const pathname = useLocation().pathname
render(
...
{
pathname === '/' ? a : b
}
...
)
uj5u.com熱心網友回復:
您可以通過幾種方式完成此操作。最簡單的方法可能是在您的組件中使用useRouteMatch鉤子Header來測驗您希望標頭在其上表現不同的路線。
const Header = () => {
const match = useRouteMatch({
pathname: '/',
exact: true
});
return (
... JSX ... apply transparent logic on match
);
}
應用程式
render() {
return (
<>
<Header />
<Switch>
<Route path='/aboutus' component={AboutUs} />
<Route path='/shop' component={Shop} />
<Route path='/' component={Home} />
</Switch>
<Footer />
</>
);
}
或者,如果Header不是函陣列件,您可以直接在 上渲染Route,或者使用withRouter高階組件進行裝飾,然后檢查locationprop。在Header在render生命周期的方法檢查this.props.location.pathname。
render() {
const { location } = this.props;
const isTransparent = location.pathname === "/";
return (
... JSX ... apply transparent logic
);
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qita/362455.html
標籤:javascript 反应 反应路由器 反应组件
上一篇:如何獲得一個單詞在陣列中的次數?
