React.createElement()
React API로 가상 요소를 생성할 때, React.createElement()로 생성한다.
인자에 주어지는 타입에 따라 React 요소를 생성하여 반환한다. 인자의 타입으로는 HTML 태그의 이름을 문자열로 전달하거나, React 컴포넌트 타입, React Fragment
를 전달 할 수 있다.
React.createElement(type, [props], [...children])
첫 번째 인자는 생성할 전달한다. → react의 컴포넌트를 전달한다.(아래의 코드를 보면 함수 컴포넌트를 전달 받은 것을 볼 수 있다. )
두 번째 인자는 (외부로부터) 전달 속성을 설정한다.
{}
중괄호로 묶어서 설정한다. 이는 객체임을 의미한다.
나머지 인자는 요소에 넣을
children
으로 전달된다.나머지 인자는 즉, react가 해석할 때,
children: 'text'
로 해석한다.
// 이 둘은 같은 속성을 가진 요소를 생성한다.
React.createElement(App, {className: 'newNode', children: 'text'})
React.createElement(App, {className: 'newNode'}, 'text')
위에서 말했듯 두번째 인자는 전달 속성 객체이기 때문에 구조 분해 할당이 가능하다.
function App(props) {
return <div className={props.className}>{props.children}</div>
}
const app = React.createElement(App, {className: 'newNode', children: 'text'})
위의 코드에서 객체 구조 분해 할당을 해보면 아래와 같이 나타낼 수 있다.
// 위의 코드에서 객체 구조 분해 할당을 해보면
function App(props) {
// {className: 'newNode', children: 'text'}
const {className, children} = props
return <div className={className}>{children}</div>
}
따로 변수를 만들지 않고 매개변수로 바로 받을 수 있다.
function App({className, children}) {
return <div className={className}>{children}</div>
}
Last updated
Was this helpful?