[英]Pass Props to Outlet in React Router v6
我無法在新的 react-router v6 中將道具傳遞給我的 Outlet 組件。 我嘗試了直接的解決方案:
render() {
return (
<Outlet name="My name" />
);
}
這正確地呈現了子組件,但是沒有道具被傳遞給孩子。 React 團隊(或與此相關的任何其他人)提供的示例都沒有顯示帶有道具的 Outlets,所以我擔心這實際上不是一回事。 有沒有其他方法我沒有找到或者我是否錯誤地使用了 Output 組件?
編輯:似乎沒有直接的方法來傳遞道具,請參閱下面的答案。
使用功能組件時,像這樣在父組件中聲明名稱。
function Parent() {
const const name='Your name'
return <Outlet context={[name]} />;
}
然后在子組件中執行此操作
//import this
import { useOutletContext } from "react-router-dom";
function Child() {
const [name] = useOutletContext();
return <p >{name}</p>;
}
這里的另一種選擇是使用Context API將道具從您的父視圖共享到您的子視圖。
const Context = React.createContext({})
function ParentView () {
const outlet = useOutlet()
return (
<Context.Provider value={{ foo: 'bar' }}>
<h1>Parent View</h1>
{outlet}
</Context.Provider>
)
}
function ChildView () {
const props = React.useContext(Context)
return (
<div>child view {props.foo}</div>
)
}
另一種選擇(未經測試)可能是使用React.cloneElement
來克隆 outlet 並向其添加 props。
在定義 Outlet 組件時,您必須定義要使用 name 道具的位置
const outlet = ( props ) => {
return (
<h1>{props.name}</h1>
);
};
不幸的是,根據這個 GitHub 問題的響應https://github.com/ReactTraining/react-router/issues ,在挖掘了一段時間之后,似乎沒有直接的方法可以做到這一點,也沒有計划改變它(至少現在是這樣) /7495 。
我這樣做並且效果很好的一種方法是創建一個到達上下文,如果您知道如何使用反應上下文,這對您來說會很容易。
在單獨的文件中創建 Context.js 以防止 require 循環
const AdminStoreContext = React.createContext();
然后導出
export{AdminStoreContext}
然后在另一個文件中創建上下文的使用者和提供者,然后導入您創建的上下文
import { AdminStoreContext } from "../../contexts";
class AdminStoreContextProvider extends React.Component {
constructor(props) {
super(props);
this.state = { ===vlaues you want to share }
}
render() {
return (
<AdminStoreContext.Provider
value={{
...this.state,//===spread the value you want to share
}}>
{
this.props.children
}
</AdminStoreContext.Provider>
);
}
}
const AdminStoreContextConsumer = AdminStoreContext.Consumer;
export { AdminStoreContextConsumer, AdminStoreContextProvider }
你可以用上下文包裝你的應用程序
<AdminStoreContextProvider>
<app/>
<AdminStoreContextProvider />
您可以使用消費者或上下文來獲取用於 Outlet 的值,我們使用上下文
再次導入它
import { AdminStoreContext } from "../../contexts";
const route[{
path: 'consumer',
element: <MyMainComponent AdminStoreContext ={AdminStoreContext } />,
children: [
{ path: 'account', element: <MySubComponent1 AdminStoreContext ={AdminStoreContext } /> },
{ path: 'purchaseHistory', element: <MySubComponent2 AdminStoreContext ={AdminStoreContext } /> }
]
},
然后在你的 MySubComponent1 或 MySubComponent2
從道具中獲取價值並使用
const { AdminStoreContext } = props;
const context = React.useContext(AdminStoreContext )
並從上下文中獲取您的價值觀,希望這對您有所幫助
context.//get any value you put on the state
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.