Heim  >  Fragen und Antworten  >  Hauptteil

Übersetzung: React – TypeScript destrukturierende Zuweisung von Requisiten

<p>Ich habe eine Funktion</p> <pre class="brush:php;toolbar:false;">Exportfunktion getSubjectsForStudent(data: any) : any[]</pre> <p>Das „Datenargument“ ist das, was ich von einer externen Quelle erhalte, und die Definition eines starken Typs ist nicht möglich. „return“ ist von „data“ abgeleitet und hat daher ebenfalls den Typ „any“. <br /><br />Eine „Haupt“-Komponente übergibt „return“ an eine „untergeordnete“ Komponente, wie folgt: </p><p><br /></ p> ; <pre class="brush:php;toolbar:false;"><MainCategories subject={getSubjectsForStudent(data)} /></pre> <p>Und in der MainCategories-Komponente </p> <pre class="brush:php;toolbar:false;">Standardfunktion exportieren MainCategories(props: any) { const tmp = props.subjects; ...</pre> <p>Übersetzung: Es funktioniert, kein Problem. </p><p>Aber ich möchte: </p><p>export default function MainCategories( {subjects} ) {</p><p>Kann jemand helfen? </p><p><br /></p>
P粉071602406P粉071602406422 Tage vor413

Antworte allen(2)Ich werde antworten

  • P粉579008412

    P粉5790084122023-07-28 12:34:25

    你需要添加一个 Props 的类型或接口,然后你就可以通过解构来获取 subjects。

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

    Antwort
    0
  • P粉155710425

    P粉1557104252023-07-28 00:35:26

    我经常使用这种模式来实现这个,但主要的关键是定义props。

    import { FunctionComponent } from 'react';
    
    interface Props {
      // In your case
      subjects: any
    }
    
    const MainCategories: FunctionComponent<Props> = ({subjects}) => (
      ...
    );
    
    export default MainCategories;

    Antwort
    0
  • StornierenAntwort