function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const Welcome = () => return <h1>Hello, {props.name}</h1>;
class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
render(){return 렌더링 시킬 엘리먼트}
로 표현한다함수 컴포넌트 | 클래스 컴포넌트 | |
---|---|---|
기능 | react hooks(useState, useEffect 등)사용 | lifecycle (componentWillMount, componentDidUpdate 등) |
표현 방법 | function Example() {return <h1>예시</h1>;} | class Example extends React.component {render () {return <h1>예시</h1>;}} |
props 넘기는 법 | props를 argument로 넘겨준다 | 아래 예시처럼 {this.props.(prop종류이름)} 로 작성하여 사용가ㄴ으 |
props 예시 | function FunctionalComp(props) {return <h1>Hii, {props.name}</h1>;} | class ClassComp extends React.Component {render() {return <h1>Hii, {this.props.name}</h1>;} |
state 관리 | useState() 사용 | constructor() 사용 |
hoisting | JS함수 선언식의 경우 호이스팅이 된다는 특징이 그대로 적용됨. 따라서 선언 전에 사용가능 | JS에서 클래스는 선언 전에 사용할 수 없다는 특징이 그대로 적용됨 |
성능 차이 | 함수 컴포넌트는 type(string)과 props(object)로 구성되어 있기 때문에 성능 면에서 더 좋음. 함수 컴포넌트의 렌더링을 위해서는 함수 호출과 props 전달만 필요해서 빠름. | 클래스 컴포넌트는 인스턴스이며, 상태를 관리하고 조작하는 constructor()를 내부에 따로 포함하고 있음. 클래스 인스턴스 생성보다 함수 호출 시간이 더 짧기 때문에 성능 면에서 함수 컴포넌트가 더 좋은 편이다. |
출처: https://www.xenonstack.com/blog/functional-vs-class-components
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Jenny" />
<Welcome name="Ari" />
<Welcome name="Cindy" />
</div>
);
}
const root = ReactDOM.createRoot(document.getElementById('root'));
root.render(<App />);
아래는 리액트 공식문서에 있는 예시이다.
사진 출처: https://ko.reactjs.org/docs/thinking-in-react.html
FilterableProductTable(노란색): 예시 전체를 담는 container
SearchBar(파란색): 모든 유저의 입력(user input) 을 받는 컴포넌트
ProductTable(연두색): 유저의 입력(user input)을 기반으로 데이터 콜렉션(data collection)을 필터링 해서 보여주는 컴포넌트
ProductCategoryRow(하늘색): 각 카테고리(category)의 헤더를 보여주는 컴포넌트
ProductRow(빨강색): 각각의 제품(product)에 해당하는 행을 보여주는 컴포넌트
컴포넌트 분리 방법 관련 보면 좋은 자료
https://ko.reactjs.org/docs/thinking-in-react.html
https://www.youtube.com/watch?v=UUga4-z7b6s
(따로 정리 예정)
https://frontarm.com/james-k-nelson/how-should-i-separate-components/
(번역예정)
https://blog.openreplay.com/understanding-the-container-component-pattern-with-react-hooks
(번역예정)
const ChildComponent = () => {
return <p>I'm the 1st child!</p>;
};
class ParentComponent extends Component {
render() {
return (
<h1>
I'm the parent component.
<ChildComponent />
<ChildComponent />
<ChildComponent />
</h1>
);
}
}
//결과
//I'm the parent component.
//I'm the 1st child!
//I'm the 1st child!
//I'm the 1st child!
예제 출처: https://itnext.io/what-is-props-and-how-to-use-it-in-react-da307f500da0