【问题标题】:React Typescript how to pass props with typesReact Typescript 如何通过类型传递道具
【发布时间】: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&lt;List people={people}/&gt; 中我遇到的人的问题

Type '{ people: IState[]; }' is not assignable to type 'IntrinsicAttributes & IProps[]'.
  Property 'people' does not exist on type 'IntrinsicAttributes & IProps[]'

如何通过类型传递 props 中的数据?

【问题讨论】:

    标签: reactjs typescript


    【解决方案1】:

    那是因为props 是顶级对象,它包含传递给组件的所有道具,所以你应该解构它,或者改变接口:

    快速修复:解构道具

    const List = ({ people }: { people: IProps[] }) => { ... }
    

    更好的解决方法:更改IProps 的类型,使其定义嵌套的people

    interface IProps{
        people: Array<{
            name: string;
            age: number;
        }>
    }
    
    const List = ({ people }: IProps) => { ... }
    

    建议

    一些额外的提示:不要在两个文件中声明相同的 prop 接口,这意味着如果你以后改变主意,你需要在多个位置更新它们,你总是可以让 List 导出 people 属性(或实际上,原子化版本,比如IPerson),然后让消费父级导入它。一个例子:

    // List.tsx
    export interface IPerson {
        name: string;
        age: number;
    }
    interface IProps {
        people: IPerson[];
    }
    const List = ({ people }: IProps) => { ... }
    

    那么……

    // App.tsx
    import List, { IPerson } from './components/List';
    const [people, setpeople] = useState<IPerson[]>([ ... ]);
    

    【讨论】:

      【解决方案2】:

      您可以在第一个文件中导出您的界面,然后在第二个文件中导入它

      export interface IState{
        name: string
        age: number
      }
      

      和在List.tsx中使用相同的接口,

      import { IState} from './List';
      

      【讨论】:

        猜你喜欢
        • 2021-11-23
        • 2018-11-22
        • 1970-01-01
        • 1970-01-01
        • 2021-04-01
        • 2021-07-21
        • 2019-08-09
        • 1970-01-01
        • 2021-12-04
        相关资源
        最近更新 更多