打字稿反应清单

Typescript React List

反应打字稿。 我想呈现此列表,但没有呈现。

我是 Typescript 的新手,我不太了解如何将道具从 App.tsx 传递到 children Technology.tsx

Technology.tsx

import React from 'react';

export type State = {
    id: number;
    name:string;
  } 
   
const Technology: React.FC <State[]>  = ({id,name}) => {
    return ( 
        <div >
            <h2 key={id}>{name}</h2>
        </div>
     );
}

export default Technology; 

App.tsx

import React,{Fragment, useState} from 'react';
import Technology from './components/Technology'

 export type State = {
  id: number;
  name:string;
} 
 
const App: React.FC = () => {

  const [items, setItems] = useState  <State[]>([
    {id:2 , name: ' Vue JS' },
    {id:3 , name: ' Node JS'},
    {id:4 , name: ' Angular JS'},
    {id:1 , name: ' React JS'}
  ])
    
  return (
    <Fragment>
        <h1>List of technologies</h1>
       {items.map(item=>(
             <Technology
               technology= {item}  
            />
        ))} 
    </Fragment>
  );
}

export default App;

<Technology> 接受的道具与您传递的道具不匹配。

export type State = {
  id: number;
  name:string;
} 
const Technology: React.FC <State[]>  = ({id,name}) => { ... }

这需要像这样的道具:

<Technology id={item.id} name={item.name} />

你必须明确地传递 idname 作为道具。


或者您可以将 Technology 的道具更改为:

export type State = {
  technology: {
    id: number;
    name:string;
  } 
}
const Technology: React.FC <State[]>  = ({technology}) => {
  return ( 
    <div >
      <h2 key={technology.id}>{technology.name}</h2>
    </div>
  );
}

现在您可以像上面那样传入单个 technology 道具:

<Technology technology={item} />