跳到主要内容

Pages

https://reflex.dev/docs/pages/overview/

Pages map components to different URLs in your app. 包含创建页面、处理 URL 参数、访问查询参数、管理页面元数据以及处理页面加载事件。

Adding a Page 添加页面

定义一个返回类型为 component 的方法,由此可创建一个 page。默认情况下,函数名称将用作路由,但您也可以指定路由。

def index():
return rx.text("Root Page")


def about():
return rx.text("About Page")


def custom():
return rx.text("Custom Route")


app = rx.App()

app.add_page(index)
app.add_page(about)
app.add_page(custom, route="/custom-route")

在此示例中,我们创建三个页面:

  • index - The root route, available at /
    • Index is a special exception where it is available at both / and /index. All other pages are only available at their specified route.
  • about - available at /about
  • custom - available at /custom-route

Page Decorator 页面装饰器

您还可以使用 @rx.page 装饰器来添加页面。

@rx.page(route="/", title="My Beautiful App")
def index():
return rx.text("A Beautiful App")

这相当于使用相同参数调用 app.add_page

Links are accessible elements used primarily for navigation. Use the href prop to specify the location for the link to navigate to.

rx.link("Reflex Home Page.", href="https://reflex.dev/")
rx.link("Example", href="/docs/library") # local link works
rx.link(
"Open in new tab",
href="https://reflex.dev/",
is_external=True,
) # open the link in a new tab

Redirect 重定向

使用 rx.redirect() 重定向到应用程序中的新路径。

  • path: The destination path or URL to which the user should be redirected.
  • external: If set to True, the redirection will open in a new tab. Defaults to False.
rx.vstack(
rx.button(
"open in tab",
on_click=rx.redirect(
"/docs/api-reference/special_events"
),
),
rx.button(
"open in new tab",
on_click=rx.redirect(
"https://github.com/reflex-dev/reflex/",
is_external=True,
),
),
)

Redirect 也可以在 State 的 event handler 中触发, meaning logic can be added behind it.

It is necessary to return the rx.redirect().

class Redirect2ExampleState(rx.State):
redirect_to_org: bool = False

@rx.event
def change_redirect(self):
self.redirect_to_org = not self.redirect_to_org

@rx.var
def url(self) -> str:
return (
"https://github.com/reflex-dev/"
if self.redirect_to_org
else "https://github.com/reflex-dev/reflex/"
)

@rx.event
def change_page(self):
return rx.redirect(self.url, is_external=True)


def redirect_example():
return rx.vstack(
rx.text(f"{Redirect2ExampleState.url}"),
rx.button(
"Change redirect location",
on_click=Redirect2ExampleState.change_redirect,
),
rx.button(
"Redirect to new page in State",
on_click=Redirect2ExampleState.change_page,
),
)

Nested Routes 嵌套路由

Pages can also have nested routes.

def nested_page():
return rx.text("Nested Page")


app = rx.App()
app.add_page(nested_page, route="/nested/page")

Page Metadata 页面元数据

You can add page metadata such as:

  • The title to be shown in the browser tab
  • The description as shown in search results
  • The preview image to be shown when the page is shared on social media
  • Any additional metadata
@rx.page(
title="My Beautiful App",
description="A beautiful app built with Reflex",
image="/splash.png",
meta=meta,
)
def index():
return rx.text("A Beautiful App")


@rx.page(title="About Page")
def about():
return rx.text("About Page")


meta = [
{"name": "theme_color", "content": "#FFFFFF"},
{"char_set": "UTF-8"},
{"property": "og:url", "content": "url"},
]

app = rx.App()

Getting the Current Page 获取当前页面

You can access the current page from the router attribute in any state.

class State(rx.State):
def some_method(self):
current_page_route = self.router.page.path
current_page_url = self.router.page.raw_path
# ... Your logic here ...

The router.page.path attribute allows you to obtain the path of the current page from the router data, 但若是 dynamic pages 的话,this will contain the slug rather than the actual value used to load the page.

router.page.raw_path 可以拿到动态路由完整的 path. This will contain all query parameters and dynamic path segments.

在上面的示例中, current_page_route 将包含路由模式(例如, /posts/[id] ),而 current_page_url 将包含实际 URL(例如, /posts/123 )。

要获取完整的 URL(包含域名的),请使用 full_ 前缀访问相同的属性。

class State(rx.State):
@rx.var
def current_url(self) -> str:
return self.router.page.full_raw_path


def index():
return rx.text(State.current_url)


app = rx.App()
app.add_page(index, route="/posts/[id]")

Dynamic Routes 动态路由

image-20250218112520875

Regular Dynamic Routes 常规动态路由

A regular dynamic route is defined by square brackets in a route string / url pattern. For example /users/[id] or /products/[category].

这些动态路由参数可以通过 State var 访问

@rx.page(route="/post/[pid]")
def post():
"""A page that updates based on the route."""
# Displays the dynamic part of the URL, the post ID
return rx.heading(rx.State.pid)


app = rx.App()

The [pid] part in the route is a dynamic segment, meaning it can match any value provided in the URL. For instance, /post/5, /post/10, or /post/abc would all match this route.

如果用户导航到 /post/5State.post_id 将返回 5 ,页面将显示 5 作为标题。如果 URL 是 /post/xyz ,它将显示 xyz 。如果 URL 是 /post/ 且没有任何额外参数,它将显示 ""

如果您正在使用 app.add_page 方法定义页面,则必须最先添加动态路由,特别是如果它们使用与非动态路由相同的函数。

Catch-All Routes 捕获所有路由

Catch-all routes in Reflex allow you to match any number of segments in a URL dynamically.

class State(rx.State):
@rx.var
def user_post(self) -> str:
args = self.router.page.params
usernames = args.get("username", [])
return f"Posts by {', '.join(usernames)}"


@rx.page(route="/users/[id]/posts/[...username]")
def post():
return rx.center(rx.text(State.user_post))


app = rx.App()

在这种情况下, ...username catch-all pattern 捕获 /users/ 后的任意数量段,允许像 /users/2/posts/john//users/1/posts/john/doe/ 这样的 URL 匹配路由。

通配符路由必须放置在 URL 模式的末尾,以确保正确的路由匹配。

Optional Catch-All Routes 可选的通配符路由

可选的通配符路由,用双方括号( [[...]] )括起来。这表示指定的段是可选的,路由可以匹配具有这些段或不具有这些段的 URL。

class State(rx.State):
@rx.var
def user_post(self) -> str:
args = self.router.page.params
usernames = args.get("username", [])
return f"Posts by {", ".join(usernames)}"


@rx.page(route="/users/[id]/posts/[[...username]]")
def post():
return rx.center(rx.text(State.user_post))


app = rx.App()