[英]How to pass props to a function and access it in a component using react and typescript?
i want to pass props along with routercomponent props and access it in a component using react and typescript.我想将道具与路由器组件道具一起传递,并使用 react 和 typescript 在组件中访问它。
i have a MainComponent which has a ChildComponent.我有一个 MainComponent,它有一个 ChildComponent。 I want to pass props namely isOpen, showdialog and hidedialog props to the ChildComponent.
我想将 isOpen、showdialog 和 hidedialog 道具传递给 ChildComponent。
Below is the code,下面是代码,
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
}
I have tried accessing like below我试过像下面这样访问
interface Props {
isOpen: boolean;
showDialog: any;
hideDialog: any;
}
function ChildComponent({ history }: RouteComponentProps) {
//how to access it here...
}
I am not knowing how to access it here.我不知道如何在这里访问它。 could someone help me fix this.
有人可以帮我解决这个问题。 thanks.
谢谢。
Just continuing destructuring it.只是继续解构它。 Just make sure your types are lined up.
只需确保您的类型排列整齐。
function ChildComponent({ history, isOpen, showDialog, hideDialog }: RouteComponentProps) {
//how to access it here...
}
Remember that object you're passing into the function is an instance of React Props, so everything that is a property on the JSX is passed in the props object under the same keys.请记住,您传递给 function 的 object 是 React Props 的一个实例,因此 JSX 上的所有属性都在同一键下的 props object 中传递。
You can define the props interface to be a combination of RouteComponentProps and ChildProps.您可以将 props 接口定义为 RouteComponentProps 和 ChildProps 的组合。 Post that destructure them from props
从道具中解构它们的帖子
interface Props {
isOpen: boolean;
showDialog: any;
hideDialog: any;
}
function ChildComponent({ history, isOpen, showDialog, hideDialog }: Props & RouteComponentProps<{}>) {
}
PS on a sidenote, a functional component doesn't have a render function so you just needed to write your MainComponent like 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.