- 컴포넌트 이름을 스트링으로 받아서 적용할 수 있음
const Header = ({children, level=1}) => { let Tag = `h${level}` return <Tag>{children}</Tag> }
- 컴포넌트들의 props를 수정해서 새로운 컴포넌트 만들기
- 여기서는 자식 컴포넌트들을 가공하는 예시
const Spacer = ({ children, type="horizontal" size=8 }) => { ... //유효한 자식 컴포넌트들의 props를 수정해서 새로운 자식들을 만듦 const nodes = React.Children.toArray(children) .filter(element=>React.isValidElement(element) && element.props.__Type === "SpacerItem") .map((element, idx, elements) => { return React.cloneElement(element, { ...element.props, style: { ...element.props.style, marginRight: type === 'horizontal' && index !== elements.length -1 ? size : undefined, marginBottom: type === 'vertical' && index !== elements.length -1 ? size : undefined, } }) }) return ( <div {...props} style={..}> {nodes} </div> )
React.children.toArray(ele)
React.isValidElement(ele)
element.props.__Type
: 가공하고 싶은 자식 컴포넌트의 props로 __Type을 지정해서 해당되는 자식만 가공하도록 함
⇒
자식컴포넌트.defaultProps ={ __Type: ‘자식컴포넌트이름’ }
으로 값을 줄 수 있다React.cloneElement(ele, props)
- 자식 컴포넌트의 props가 외부 상태 등에 따라, 즉 자식 컴포넌트와 독립적인 로직으로 인해 바뀔 때 이 방법을 쓰면 좋음
- 보통 스피너 같은 아이콘은 이렇게 만듦
<i> <svg>...</svg> //스피너 svg </i>
- 클립보드 복사 코드
navigator.clipboard.writeText(스트링)