简体   繁体   English

React - 道具的 TypeScript 解构

[英]React - TypeScript destructuring of props

I have a function:我有一个功能:

 export function getSubjectsForStudent(data: any) : any[]

"data argument" I receive from external source and it's not feasible to define strong type. “数据参数”我从外部来源收到,定义强类型是不可行的。 "return" is derived from "data" so it's of type any as well. “return”源自“data”,因此它的类型也是 any 。

A "Main" component passes "return" to a "child" component like this: “主”组件将“返回”传递给“子”组件,如下所示:

<MainCategories subjects={getSubjectsForStudent(data)} />

And in MainCategories在 MainCategories 中

export default function MainCategories(props: any) {
    const tmp = props.subjects;
    ...

It works and it's Ok.它有效并且没问题。

But I want但我想要
export default function MainCategories( {subjects} ) {导出默认函数 MainCategories( {subjects} ) {

Can anybody help with it?有人可以帮忙吗?

I often use this pattern to do that, but the main point is to define the props.我经常使用这种模式来做到这一点,但重点是定义道具。

import { FunctionComponent } from 'react';

interface Props {
  // In your case
  subjects: any
}

const MainCategories: FunctionComponent<Props> = ({subjects}) => (
  ...
);

export default MainCategories;

You need to add a type/interface of Props - Then you'll be able to get subjects by destructuring.您需要添加 Props 的类型/接口 - 然后您将能够通过解构获得主题。

interface Props {
  subjects: any
}

export default function MainCategories({ subjects }: Props) {
    const tmp = props.subjects;
    ...

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM