【发布时间】:2022-01-06 20:11:08
【问题描述】:
尝试在 React 中使用 Typescript 变得更好
我有一个超级简单的应用程序,其中有 App.tsx 和一个用于对象数组的 useState
import List from './components/List';
interface IState{
name: string
age: number
}
function App() {
const [people, setpeople] = useState<IState[]>([
{
name: 'Chris',
age: 20
},
{
name: 'John',
age: 28
},
{
name: 'Paul',
age: 23
}
])
return (
<div className="App">
<List people={people}/>
</div>
);
}
export default App;
我想将此作为道具传递给另一个组件List.tsx。
interface IProps{
name: string
age: number
}
const List = (people:IProps[]) => {
return (
<div>
{people.map(person => (
<h2>{person.name}</h2>
))}
</div>
);
};
export default List;
我在App.tsx 中有对象的类型,我正在尝试在List.tsx 中使用相同的类型
App.tsx<List people={people}/> 中我遇到的人的问题
Type '{ people: IState[]; }' is not assignable to type 'IntrinsicAttributes & IProps[]'.
Property 'people' does not exist on type 'IntrinsicAttributes & IProps[]'
如何通过类型传递 props 中的数据?
【问题讨论】:
标签: reactjs typescript