Typescript
Typescript (2) Props
오리888
2023. 3. 4. 14:53
Component를 부를 때 props를 주곤 한다
예) Square component에 bgColor props를 주었다
import React from "react";
import Square from "./Square";
function App() {
return (
<div>
<Square bgColor="teal" />
</div>
);
}
export default App;
이렇게 square component에 props를 준 뒤에는 square component에서 props를 받아야 되는데 간단하다
예)
import styled from "styled-components";
const Wrapper = styled.div``;
function Square({bgColor}) {
return <Wrapper />;
}
export default Square;
이런 식으로 props를 component에서 받을 수 있는데 typescript는 bgColor props에 대해 에러를 띄운다
그 이유는 바로 bgColor type에 대해 설명을 안 해줬기 때문이다 bgColor이 string인지 number인지 지정을 해놔야 되기 때문이다
지정을 해주는 방법은 간단한데 바로 interface를 쓰는 것이다
예) bgColor은 색깔이기 때문에 string으로 지정해 주었다
import styled from "styled-components";
const Wrapper = styled.div``;
interface bgColorProps {
bgColor: string;
}
function Square({ bgColor }: bgColorProps) {
return <Wrapper />;
}
export default Square;
이렇게 interface를 만든 뒤 component에게 interface를 넣어주면 된다