简体   繁体   中英

Passing Interface props in functional component in Typescript

Error:

在此处输入图像描述

Actually, I can solve this error if I add a question mark on my interface. However, I expected it should work without a question mark. Am I missing something or is it right to add a question mark?

This is 'Main.tsx'

import * as React from 'react';

interface ICamp {
  id: number;
  type: 'popular' | 'specialDiscount';
  dateStart: string;
  thumbnail: string;
  campName: string;
  //인가 부트 캠프
  status?: '모집전' | '모집중' | '모집완료';
  //특가 할인 캠프
  category?: string;
  //커뮤니티
  tag?: '조회수 TOP' | '취업 고민';
}

// export default function Main(props: ICamp) {
//   return <div style={{ backgroundColor: 'red' }}>This is main</div>;
// }

export const Main: React.FC<ICamp> = ICamp => {
  return <div style={{ backgroundColor: 'red' }}>This is main</div>;
};

This is Router.tsx

import { BrowserRouter, Routes, Route } from 'react-router-dom';
import Nav from './components/Nav/Nav';
import { Main } from './main/Main';
import Detail from './detail/Detail';
import Footer from './components/Footer/Footer';

function Router() {
  return (
    <BrowserRouter>
      <Nav />
      <Routes>
        <Route path="/" element={<Main />} />
        <Route path="/main" element={<Main />} />
        <Route path="/detail" element={<Detail />} />
      </Routes>
      <Footer />
    </BrowserRouter>
  );
}
export default Router;

Because you have to pass at least the following props to the component:

id: number;
type: 'popular' | 'specialDiscount';
dateStart: string;
thumbnail: string;
campName: string;

like that:

element={<Main id={1} ... />} />

You are creating a functional component and tell TypeScript, that you want to pass mandatory props data to this component. If you don't need to pass any props to your component, you can mark them as "optional" by adding a question mark.

By reading your code for the router, I see you don't have passed in that mandatory props data and thus, TypeScript will throw an error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM