Translation: React - TypeScript destructuring assignment of props
P粉071602406
P粉071602406 2023-07-27 16:35:13
0
2
428
<p>I have a function</p> <pre class="brush:php;toolbar:false;">export function getSubjectsForStudent(data: any) : any[]</pre> <p>The "data argument" is what I receive from an external source and defining a strong type is not feasible. "return" is derived from "data", so it is also of type any. <br /><br />A "Main" component passes "return" to a "child" component, like this: </p><p><br /></ p> <pre class="brush:php;toolbar:false;"><MainCategories subjects={getSubjectsForStudent(data)} /></pre> <p>And in the MainCategories component, </p> <pre class="brush:php;toolbar:false;">export default function MainCategories(props: any) { const tmp = props.subjects; ...</pre> <p>Translation: It works, no problem. </p><p>But I want: </p><p>export default function MainCategories( {subjects} ) {</p><p>Can anyone help? </p><p><br /></p>
P粉071602406
P粉071602406

reply all(2)
P粉579008412

You need to add a Props type or interface, and then you can obtain subjects through destructuring.

interface Props {
  subjects: any
}

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

I often use this pattern to achieve this, but the main key is defining the props.

import { FunctionComponent } from 'react';

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

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

export default MainCategories;
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!