가장 간단하게 컴포넌트를 정의하는 방법은 자바스크립트 함수를 작성하는 것.
function Welcom(props) {
return <h1>Hello, {props.name}</h1>;
}
컴포넌트 구성 요소, 리액트 생명주기를 모두 포함하고 있다.
프로퍼티, state, 생명주기 함수가 필요한 구조의 컴포넌트를 만들 때 사용.
class Welcome extends React.Component {
// 생성자
constructor(props) {
super(props);
}
// 클래스형 컴포넌트는 render() 필수
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
const element = <Welcome name='Vanlan' />;
컴포넌트는 자신의 출력에 다른 컴포넌트를 참조할 수 있다.
const Header = (props) => {
return (
<div>{props.title}</div>
);
};
function App() {
return (
<div className='App'>
// Header 컴포넌트에 props로 title속성을 전달해 재사용.
<Header title={'Learn React A'} />
<Header title={'Learn React B'} />
<Header title={'Learn React C'} />
</div>
);
}
props는 읽기 전용이다.
(모든 React 컴포넌트는 props를 다룰 때 반드시 순수 함수처럼 동작해야 한다.)
props.children: 컴포넌트의 열린태그와 닫힌태그 사이에 입력되는 자식값.
// 1. 사용자 정의 컴포넌트가 일반적인 html 태그의 구조와 비슷할 때.
export default function Button(props) {
return <button onClick={props.handleClick}>{props.children}</button>
}
<Button onClick={() => alert('submit')}>제출하기</Button>
<Button onClick={() => alert('delete')}>삭제하기</Button>
<Button onClick={() => alert('add')}>추가하기</Button>
// 2. 컴포넌트에 다른 컴포넌트를 전달해야 할 때.
<Layout><Apage /></Layout>
<Layout><Bpage /></Layout>
<Layout><Cpage /></Layout>