[231130] cloneElement, 컴포넌트 타입 제너릭하게 구성 스킬

cloneElement

  • 새로운 React 요소를 생성할 수 있다.
  • 현재는 Legacy APIs (사용 추천하지 않음)
  • 공식 홈페이지
const clonedElement = cloneElement(<Row title="Cabbage" />, {
  isHighlighted: true,
})

컴포넌트 타입 제너릭하게 구성 스킬

  • props가 다른 페이지가 여러 개 있는 상황
  • page 번호를 map idx를 통해 매기고 싶은 상황
function renderCountComponentJsx<T extends {}>(
  Component: React.ComponentType<T>,
  index: number
) {
  return function (props: Omit<T, "curPage">) {
    const newProps = { ...props, curPage: index } as unknown as T

    return <Component {...newProps} />
  }
}
const pageList = [
  {
    component: Page1,
    props: {
      totalPage,
      commonColors,
      commonImages,
    },
  },
  {
    component: Page2,
    props: {
      totalPage,
      commonColors,
      highlightBgColor: "#FA4771",
      callColor: "#61B2D0",
    },
  },
]
{
  pageList.map((com, idx) => {
    const CountedComponent = renderCountComponentJsx(com.component, idx + 1)
    return (
      <ContentDiv>
        <CountedComponent {...com.props} />
      </ContentDiv>
    )
  })
}

Categories:

Updated:

Leave a comment