本页还没有译文
本页 13 段还没译成简体中文,下面显示的是英文原文。useOutletContext
还没翻译译自英文(reactrouter.com)本页 13 段都还没译
useOutletContext
Framework Data Declarative
Summary
Returns the parent route <Outlet context>.
Often parent routes manage state or other values you want shared with child
routes. You can create your own context provider
if you like, but this is such a common situation that it's built-into
<Outlet>.
// Parent route
function Parent() {
const [count, setCount] = React.useState(0);
return <Outlet context={[count, setCount]} />;
}// Child route
import { useOutletContext } from "react-router";
function Child() {
const [count, setCount] = useOutletContext();
const increment = () => setCount((c) => c + 1);
return <button onClick={increment}>{count}</button>;
}If you're using TypeScript, we recommend the parent component provide a custom hook for accessing the context value. This makes it easier for consumers to get nice typings, control consumers, and know who's consuming the context value.
Here's a more realistic example:
src/routes/dashboard.tsx
import { useState } from "react";
import { Outlet, useOutletContext } from "react-router";
import type { User } from "./types";
type ContextType = { user: User | null };
export default function Dashboard() {
const [user, setUser] = useState<User | null>(null);
return (
<div>
<h1>Dashboard</h1>
<Outlet context={{ user } satisfies ContextType} />
</div>
);
}
export function useUser() {
return useOutletContext<ContextType>();
}src/routes/dashboard/messages.tsx
import { useUser } from "../dashboard";
export default function DashboardMessages() {
const { user } = useUser();
return (
<div>
<h2>Messages</h2>
<p>Hello, {user.name}!</p>
</div>
);
}Signature
function useOutletContext<Context = unknown>(): ContextReturns
The context value passed to the parent Outlet component
AI 翻译查看英文原文