
react에서도 드디어 Components와 Props가 나왔다.
Vue에서 자주 보던 개념이라 반갑다. 어서오고
function Welcome(props){ return <h1>Hello,{props.name}</h1> }
class WelcomeClass extends React.Component{ render(){ return <h1>Hello,{this.props.name}</h1> } }
현재 두가지의 컴포넌트 타입은 똑같이 작동한다.
함수와 클래스, 둘 다 각각의 추가기능이 있다고 하는데 문서에서는 이후에 배운다고 한다.
const element = ( <div> <Welcome name="function"/> <WelcomeClass name="class"/> <h2>It is {new Date().toLocaleTimeString()}.</h2> <App/> </div> ); root.render(element);
Attribute처럼 값을 넣어주면 컴포넌트의 parameter에서 객체로 받을 수 있는듯하다.
const Comment = (props) => { return (<div className="Comment"> <UserInfo user={props.author} /> <div className="Comment-text"> {props.text} </div> <div className="Comment-date"> {formatDate(props.date)} </div> </div>) } function UserInfo(props) { return <div className="UserInfo"> <Avatar user={props.user} /> <div className="UserInfo-name"> {props.user.name} </div> </div> } function Avatar(props) { return ( <img className="Avatar" src={props.user.avatarUrl} alt={props.user.name} /> ); } const formatDate = (date) => { return new Date(date).toLocaleDateString(); } const comment = { date: new Date(), text: 'I hope you enjoy learning React!', author: { name: 'Hello Kitty', avatarUrl: 'http://placekitten.com/g/64/64' } }; const element = ( <div> <Welcome name="function" /> <WelcomeClass name="class" /> <h2>It is {new Date().toLocaleTimeString()}.</h2> <App /> <Comment date={comment.date} text={comment.text} author={comment.author} /> </div> ); root.render(element);
Vue와 마찬가지로 컴포넌트를 분리하여 처리할 수 있다.
JSX에서 class의 경우는 예약어와 중복되므로 className으로 작성해야한다고 한다.
Vue와 마찬가지로 전달받은 Props는 컴포넌트 내부에서 직접 수정하면 안되고, 읽기전용으로 써야한다고 한다.
다음 챕터에서는 드디어 state!!.