[英]How to pass props to a function and access it in a component using react and typescript?
我想將道具與路由器組件道具一起傳遞,並使用 react 和 typescript 在組件中訪問它。
我有一個 MainComponent,它有一個 ChildComponent。 我想將 isOpen、showdialog 和 hidedialog 道具傳遞給 ChildComponent。
下面是代碼,
function MainComponent() {
render= () => {
return(
<Route
exact
path="/items"
render={routeProps => (
<Layout>
<ChildComponent
isOpen={isOpen}// how to access this
showDialog={showDialog} //how to access this
hideDialog={hideDialog} //how to access this
{...routeProps}
/>
<Layout>
)}
/>
)
}
}
function ChildComponent({ history }: RouteComponentProps) {
//some logic
}
我試過像下面這樣訪問
interface Props {
isOpen: boolean;
showDialog: any;
hideDialog: any;
}
function ChildComponent({ history }: RouteComponentProps) {
//how to access it here...
}
我不知道如何在這里訪問它。 有人可以幫我解決這個問題。 謝謝。
只是繼續解構它。 只需確保您的類型排列整齊。
function ChildComponent({ history, isOpen, showDialog, hideDialog }: RouteComponentProps) {
//how to access it here...
}
請記住,您傳遞給 function 的 object 是 React Props 的一個實例,因此 JSX 上的所有屬性都在同一鍵下的 props object 中傳遞。
您可以將 props 接口定義為 RouteComponentProps 和 ChildProps 的組合。 從道具中解構它們的帖子
interface Props {
isOpen: boolean;
showDialog: any;
hideDialog: any;
}
function ChildComponent({ history, isOpen, showDialog, hideDialog }: Props & RouteComponentProps<{}>) {
}
PS 在旁注中,功能組件沒有渲染 function 所以你只需要編寫你的 MainComponent 像
function MainComponent() {
return(
<Route
exact
path="/items"
render={routeProps => (
<Layout>
<ChildComponent
isOpen={isOpen}
showDialog={showDialog}
hideDialog={hideDialog}
{...routeProps}
/>
<Layout>
)}
/>
)
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.