要使用React路由器中的<route></route>
組件來定義路由,請主要在路由器組件中使用它,例如<browserrouter></browserrouter>
或<hashrouter></hashrouter>
。 <route></route>
組件負責呈現path
時匹配當前URL。這是使用它的方法:
<code class="jsx">import { BrowserRouter, Route } from 'react-router-dom'; function App() { return ( <browserrouter> <div> <route path="/" component="{Home}"></route> <route path="/about" component="{About}"></route> <route path="/contact" component="{Contact}"></route> </div> </browserrouter> ); }</code>
在此示例中,定義了三個路線:
Home
組件。About
組件。Contact
組件。 <route></route>
組件可以以不同的方式使用以傳遞要渲染的組件:
component
支柱。render
道具,這使您可以將組件與其他道具進行渲染。children
支柱,無論其路徑是否與當前的URL匹配,都可以渲染組件。 React路由器中的<route></route>
組件支持幾個定義其行為和渲染邏輯的道具。這是主要道具:
path
:路由應匹配的字符串或字符串。如果未指定,路由將始終匹配。component
:當位置匹配path
時,一個反應組件呈現。該道具與render
和children
相互排斥。render
:位置匹配時將React元素返回到渲染的函數。當您需要將其他道具傳遞給組件或需要進行內聯渲染時,有用。children
:返回反應元素的功能。它使該路線是否與該路徑相匹配,使其可用於動畫或其他想要渲染某些東西的情況,無論當前位置如何。exact
:一個布爾值,如果整個URL路徑匹配,而不僅僅是前綴,則只有在整個URL路徑匹配時才能使路線匹配。strict
:一個布爾值,如果是的,則將在這path
中的落後斜線變得重要。location
:代表當前位置的對象。這通常用於嵌套路由器。sensitive
:一個布爾值,如果是的,則會使路線對案例敏感。使用這些道具,您可以配置<route></route>
組件以適合應用程序中的各種路由需求。
React路由器中的<route></route>
組件通過嵌套路由的概念支持嵌套路由,這允許更複雜和有組織的路由結構。這是您可以實現嵌套路線的方式:
children
道具:在父路由的組件中,您可以使用其他<route></route>
組件來定義嵌套路由。這可以通過使用children
道具或直接定義父組件中的嵌套路線來完成。這是嵌套路由的示例:
<code class="jsx">import { BrowserRouter, Route, Link } from 'react-router-dom'; function App() { return ( <browserrouter> <div> <route path="/" component="{Home}"></route> <route path="/users" component="{Users}"></route> </div> </browserrouter> ); } function Users({ match }) { return ( <div> <h2>Users</h2> <ul> <li> <link to="{`${match.url}/user1`}">User1</li> <li> <link to="{`${match.url}/user2`}">User2</li> </ul> <route path="{`${match.path}/:userId`}" component="{User}"></route> </div> ); } function User({ match }) { return <h3>User {match.params.userId}</h3>; }</code>
在此示例中, /users
路由渲染Users
組件,然後使用嵌套<route></route>
為特定用戶定義路由(例如, /users/user1
)。作為道具傳遞的match
對像有助於構造嵌套路由的相對URL。
exact
道具與<route></route>
組件一起使用,以確保路由路徑與整個URL路徑匹配,而不僅僅是與之匹配。當您想避免進行無意的比賽時,這特別有用。
您可以使用exact
道具:
<code class="jsx">import { BrowserRouter, Route } from 'react-router-dom'; function App() { return ( <browserrouter> <div> <route exact path="/" component="{Home}"></route> <route path="/about" component="{About}"></route> </div> </browserrouter> ); }</code>
在此示例中:
"/"
路線使用exact
道具。這意味著它只能匹配root URL( "/"
),而不像"/about"
這樣的URL匹配。exact
道具,則家用路線( "/"
)也將與"/about"
這樣的URL匹配,這通常不是您想要的。當在更一般的路線下定義更具體的路線時, exact
道具變得尤為重要。例如,如果您有儀表板( "/dashboard"
)的路由,而另一個用於儀表板中特定部分的路由( "/dashboard/settings"
),則可能需要使用儀表板路由以防止其與設置exact
相匹配。
總而言之, exact
支持確保了通往當前URL的路徑路徑的精確匹配,從而避免了具有更具體路徑的意外匹配。
以上是您如何使用&lt; route&gt;如何定義路線 成分?的詳細內容。更多資訊請關注PHP中文網其他相關文章!