[英]Link to(react-router-dom) conditional rendering when a button is clicked
[英]React Router: How to redirect to a different component when a link/button is clicked?
最近剛開始學習網絡開發,所以請原諒我可能很幼稚的問題。
我見過很多使用<Link>
和<Route>
來更新頁面的例子。 但是,大多數包含鏈接所在的固定導航欄,組件本身只有 static 內容。
如果鏈接/按鈕位於子組件內,我還不清楚如何正確更新頁面。 例如,給定一個容器:
<div id='container'><h1>components should be rendered in here, but only 1 at a time.</h1></div>
和 2 個組件,C1 和 C2:
class C1 extends React.Component {
/*other functions*/
render() {
return(
<div>
<p>Other things</p>
<Button>Click me to Redirect to C2!</Button>
</ div>
)
}
}
class C2 extends React.Component {
/*other functions*/
render() {
return(
<div>
<p>Other things</p>
<a>Click me to Redirect to C1!</a>
<p>Other things</p>
</ div>
)
}
}
假設這兩個組件將在“容器”div 下呈現,C1 是默認組件。 我應該如何設置 react-router 以在 C1 和 C2 之間導航,理論上用於兩個以上的組件?
react-router
和react-router-dom
是兩個互補的庫,可幫助您使用瀏覽器歷史記錄 api 使用Javascript 歷史記錄 ZEFE90A8E6004A7C8743下的 ZEFE90A8E6004A7C8743。
要實現你想要的,你應該在react-router-dom
中使用BrowserRouter
、 Switch
和Route
組件。 BrowserRouter
充當其某些實用程序的子級以及歷史記錄所在的當前位置(當前主機名、路徑名、queryParams 等)的提供者,而Switch
和Route
則通過Route
作為將您想要的路徑與 React 綁定的組件一起工作渲染和Switch
組件檢查其所有子Route
和渲染第一個與歷史記錄具有的當前路徑名匹配的組件,您可以添加不帶path
道具的Route
以便Switch
回退到它以防當前歷史記錄位置不匹配。
一個例子是這樣的
import React from 'react'
import {BrowserRouter, Switch, Route} from 'react-router-dom'
import C1 from './C1'
import C2 from './C2'
export default class App extends React.Component {
constructor(props) {
super(props);
}
render() {
return <div id="container">
<BrowserRouter>
<Switch>
<Route path="/view1" component={C1}/>
<Route path="/view2" component={C2}/>
<Route component={C1} />
</Switch>
</BrowserRouter>
</div>;
}
}
現在,有多種方法可以瀏覽聲明的頁面。 一種是直接使用Link
組件並使用“to”道具將您想要的路徑名傳遞給 go。
class C2 extends React.Component {
/*other functions*/
render() {
return(
<div>
<p>Other things</p>
<Link to="/view1">Click me to Redirect to C1!</Link>
<p>Other things</p>
</ div>
)
}
}
Link
實際上使用您通過to
屬性提供的href
呈現錨點。
另一種導航方法是使用歷史 api ,它在從 Route 渲染時作為道具注入。 這允許您在實際設置新位置之前添加更多邏輯。 這是一個簡單的例子
class C2 extends React.Component {
/*other functions*/
redirectToC1(){
// do some extra logic you may want
this.props.history.push("/view1")
}
render() {
return(
<div>
<p>Other things</p>
<a onClick={() => this.redirectToC1()}>Click me to Redirect to C1!</a>
<p>Other things</p>
</ div>
)
}
}
請務必深入了解文檔以查看更多信息。
您可以將組件作為函數調用,例如:
export default class App extends React.Component {
constructor() {
super();
this.state = {
isActive: true
};
}
C1 = () => {
return <h1>C1</h1>;
};
C2 = () => {
return <h1>C2</h1>;
};
render() {
return <div id="container">{this.state.isActive ? this.C1 : this.C2}</div>;
}
}
上面的例子沒有使用任何路由器。 您可以在此處查看如何安裝和使用反應導航的文檔: https://reactnavigation.org/docs/hello-react-navigation
你可以使用 Scrollintoview 你可以查看我制作的這個小演示以供參考演示
這個stackoverflow也很有用
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.