자식이 배열인지 확인하는 React 함수 구성 요소가 있습니다. 배열이 아니면 반환합니다. 그렇지 않으면 자식을 매핑하고 일부 JSX를 반환합니다.
import React from 'react'
interface Props {
children: React.ReactNode
}
const LineBreak: React.FC<Props> = ({ children }): any => {
if (!Array.isArray(children)) return children
return (
<>
{children.map((child, i, arr) => {
if (i + 1 === arr.length) return child
return <>{child}<br /></>
})}
</>
)
}
export default LineBreak
제가하고 싶은 것은 any
7 번 줄을 바꾸는 것입니다. 논리적으로 그것을 변경하는 React.ReactNode
것으로 충분 하다고 생각 하지만 유형 오류가 발생합니다.
Type '({ children }: PropsWithChildren<Props>) => ReactNode' is not assignable to type 'FC<Props>'. Type 'ReactNode' is not assignable to type 'ReactElement<any, any>'. Type 'string' is not assignable to type 'ReactElement<any, any>'.ts(2322)
이 오류 메시지를 올바르게 읽는 방법에 대한 몇 가지 지침을 실제로 사용할 수 있습니다.
또한 string|React.ReactNode
제한된 typescript 지식에서 React.ReactNode에 유형 문자열이 포함되어 있기 때문에 반환 유형을로 변경 하여이 오류 메시지를 우회하려고 시도 했으며 동일한 오류를 예상했습니다.
@amaster의 솔루션이 좋습니다. 오류 메시지에 대한 이해를 추가하기 만하면
이것이 오류의 의미라고 생각합니다
오류는 예상되는 반환 유형 FC<Props>
이ReactElement<any, any>
따라서 Type '({ children }: PropsWithChildren<Props>) => ReactNode' is not assignable to type 'FC<Props>'.
ReactNode의 반환 유형이 예상되는 반환 유형과 일치하지 않음을 의미합니다.FC<Props>
그리고 Type 'ReactNode' is not assignable to type 'ReactElement<any, any>'.
예상되는 대신 ReactNode를 반환 유형으로 할당하려고한다는 것입니다.ReactElement<any, any>
이 기사는 인터넷에서 수집됩니다. 재 인쇄 할 때 출처를 알려주십시오.
침해가 발생한 경우 연락 주시기 바랍니다[email protected] 삭제
몇 마디 만하겠습니다