여기에는 버튼 컴포넌트가 다시 있지만 이번에는 임의의 내용이 포함된 객체를 반환합니다.
interface Props {
className: string;
}
/* @ts-expect-error */
export const Button = (props: Props) => {
return {
ohDear: "123",
};
};
const Parent = () => {
return (
<>
<Button className="my-class"></Button>
</>
);
};
Parent
내부에 버튼의 반환 타입이 JSX 요소가 아니라는 오류가 발생했습니다.
이를 가능하게 하는 타입 선언을 찾으십시오
export const Button: unknown = (props: Props) => {
...
unknown
부분을 대체하십시오
해결책은 버튼에 React.FC
타입 정의를 적용하는 것입니다.
export const Button: React.FC = (props: Props) => {
return {
ohDear: "123",
};
};
@ts-expect-error
를 제거하면 ohDear: string
가 포함된 객체를 반환할 수 없다는 불만을 제기하는 몇 가지 오류가 표시됩니다.
Type '(props: {}) => { ohDear: string; }' is not assignable to type 'FC<{}>'
Type '{ ohDear: string; }' is missing the following properties from type 'ReactElement<any, any>': type, props, key
리턴을 <div />
또는 null
로 변경하면 버튼 컴포넌트는 유효한 React 엘리먼트이므로 오류가 제거되지만, 이제 부모 컴포넌트에서 오류가 발생합니다.
export const Button: React.FC = (props: Props) => {
return null;
};
const Parent = () => {
return (
<>
<Button className="my-class"></Button>
// error under className
</>
);
};
기본적으로 React.FC
에 prop
이 포함되어 있지 않아 props를 전달할 수 없기 때문입니다.