[英]How to access props in the component using react and typescript?
i want to access props in the react functional component using react and typescript.我想使用 react 和 typescript 访问反应功能组件中的道具。
I have the MainComponent which has Layout component and i pass prop isOpen to Layout component from MainComponent like in below code,我有具有 Layout 组件的 MainComponent,并且我将 prop isOpen 从 MainComponent 传递给 Layout 组件,如下面的代码所示,
const Layout: React.FC = ({children}) => ( //how to access isOpen prop here
<>
<leftNav />
{children}
<RightNav isOpen={isOpen} />
</>
);
interface Props {
item: item;
}
function Main({ item }: Props) {
return (
<Wrapper>
<Switch>
<Route
path="/items"
render={routeProps => (
<Layout isOpen={isOpen}> //passing prop here
<Items />
</Layout>
)}
/>
</Switch>
</Wrapper>
)
}
I have tried to access it like below我试图像下面一样访问它
interface Props {
children: any;
isOpen: boolean;
}
const Layout: React.FC = ({children, isOpen}: Props) => (
<>
<leftNav />
{children}
<RightNav isOpen={isOpen} />
</>
);
But the above throws error jsxelement is not assignable to type FC component.但是上面会抛出错误 jsxelement is not assignable to type FC 组件。
could someone help me fix this.有人可以帮我解决这个问题。 thanks.
谢谢。
You need to type the props for the FC
generic:您需要键入
FC
泛型的道具:
//interface Props { ... }
const Layout: React.FC<Props> = ({children, isOpen}) => (
<>
<leftNav />
{children}
<RightNav isOpen={isOpen} />
</>
);
or omit the FC
altogether:或完全省略
FC
:
//interface Props { ... }
const Layout: ({children, isOpen}: Props) => (
<>
<leftNav />
{children}
<RightNav isOpen={isOpen} />
</>
);
React.FC is generic and takes a type argument for the props. React.FC 是通用的,并为 props 提供类型参数。 You can write your layout component like this.
您可以像这样编写布局组件。
interface Props {
isOpen: boolean;
// if you want isOpen props to be optional
// isOpen?: boolean;
}
const Layout: React.FC<Props> = ({children, isOpen}) => (
<>
<leftNav />
{children}
<RightNav isOpen={isOpen} />
</>
);
Your main component is fine.您的主要组件很好。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.