react-router-dom v6 里的 Outlet 子组件如何向父组件传参?

2022-03-16 16:17:02 +08:00
 Chism

父向子传可以用 useOutletContext ,但是子向父传就无法通过 useOutletContext 了

有什么办法做到<Ooulet />里的子组件给父组件传参?

需求是父组件需要响应<Ooulet />子组传递过来的数据

2497 次点击
所在节点    React
12 条回复
ahwwh1994
2022-03-16 16:28:42 +08:00
传函数过去啊,和 props 一样的啊
Chism
2022-03-16 16:30:09 +08:00
@ahwwh1994
<Ooulet />里无法传函数回去
liuzhaowei55
2022-03-16 16:38:40 +08:00
父组件用 useState 定义,然后把 state setState 都传下去,子组件 setState 就可以了
liuzhaowei55
2022-03-16 16:39:39 +08:00
@Chism 用中括号把 state setState 放一起往下传
Chism
2022-03-16 16:40:37 +08:00
@liuzhaowei55
原来如此,我试试。
之前没用 router 时,直接 const 定义个函数给子组件,子组件执行函数,父组件也响应。
用了 Outlet 就不行,我试试你的方法,多谢。
agdhole
2022-03-16 16:48:11 +08:00
用个状态管理库也可以,比如 recoil
ahwwh1994
2022-03-16 16:57:56 +08:00
Chism
2022-03-16 17:36:16 +08:00
@ahwwh1994
抱歉,你是对的,已验证。多谢回帖
Chism
2022-03-16 17:37:32 +08:00
@agdhole
周下载 20 万,应该不错,多谢提醒
KalaSearch
2022-03-23 13:06:05 +08:00
可以尝试:

```

type AuthUserContextType = {
authedUser: UserResponse;
};

const useAuthUserContext = (): AuthUserContextType => {
return useOutletContext<AuthUserContextType>();
};

// 然后在你的组件中:

const ctx: AuthUserContextType = {
authedUser: YOUR_DATA,
};

return <Outlet context={ctx} />;

```
KalaSearch
2022-03-23 13:06:43 +08:00
oops... 抱歉没整理好格式

这个问题上周刚碰到,你感兴趣的话我可以写篇博客说一下
Chism
2022-03-23 14:30:05 +08:00
@KalaSearch
我按照 1 楼的方法也成功了。。

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://www.v2ex.com/t/840789

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX