REACT main concept — 1
ReactDOM.render(
<h1>Hello, world!</h1>,
document.getElementById('root')
);
root에 <h1>태그를 생성, append.
const element = <h1>Hello, world!</h1>;
element는 string도 아니고, HTML element도 아님.
‘JSX’라는 것인데, 자바스크립트의 확장 용법이다.
마크업(html)과 로직(js)를 분리해서 사용하는 것 대신,
리액트는 그 둘을 loose하게 coupled한 ‘component’를 통해 구현한다.
function formatName(user) {
return user.firstName + ' ' + user.lastName;
} // 들어온 object의 firstName과 lasName을 return하는 펑션
const user = {
firstName: 'Harper',
lastName: 'Perez'
};
const element = (
<h1>
Hello, {formatName(user)}!
</h1>
); // 자바스크립트 펑션의 실행 결과를 {}를 통해 주입.
ReactDOM.render(
element,
document.getElementById('root')
);
quote를 통해, 속성으로서string literal을 선언할 수 있다.
const element = <div tabIndex="0"></div>;
JSX prevents injection attack (like xss, cors)
const title = response.potentiallyMaliciousInput;
// This is safe:
const element = <h1>{title}</h1>;const element = (
<h1 className="greeting">
Hello, world!
</h1>
);위와 아래는 동일한 코드이다.const element = React.createElement(
'h1',
{className: 'greeting'},
'Hello, world!'
);차이점 : createElement 결과로 만들어지는 object - React elementsconst element = {
type: 'h1',
props: {
className: 'greeting',
children: 'Hello, world!'
}
};
Rendering Elements
element는 리액트 앱의 가장 작은 블록 단위이다.
const element = <h1>Hello, world</h1>;
ReactDOM.render(element, document.getElementById('root'));
엘레먼트를 조합하여 component를 만든다.
element는 immutable하다.
생성 이후, 자식이나 attribute를 변화시킬 수 없다.
따라서, UI를 변화시키기 위해서는, 새로운 element를 생성,
ReactDOM.render()로 넘겨주는 수 밖에.
이런식으로.
function tick() {
const element = (
<div>
<h1>Hello, world!</h1>
<h2>It is {new Date().toLocaleTimeString()}.</h2>
</div>
);
ReactDOM.render(element, document.getElementById('root'));
}
setInterval(tick, 1000);
결과로 react는 필수적으로 적용해야하는 변경사항만 DOM에 적용한다.
Components and Props
component는 UI를 독립적이고, 재사용사능한 조각들로 나눌 수 있게한다.
개념적으로, component는 js의 function과 비슷하다.
component를 생성하는 가장 쉬운 방법은, js function 선언이다.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}es6 class개념 적용시 class Welcome extends React.Component {
render() {
return <h1>Hello, {this.props.name}</h1>;
}
}
이 function이 component라고 명백하게 구분 할 수 있는 이유는,
이 펑션은 하나의 ‘props’를 받고, react element를 리턴하기 때문이다.
우리는 이러한 component를 ‘function component’라고 한다.
Rendering a Component
먼저 DOM 태그를 대변하는 react element를 보자.
const element = <div />;
element는 유저가 정의한 component일 수도 있다.
const element = <Welcome name="Sara" />;
이 경우, JSX속성을 이 componenet에게 하나의 객체형태로 전달한다.
우리는 이것을 ‘props’라고 한다.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
const element = <Welcome name="Sara" />;
ReactDOM.render(
element,
document.getElementById('root')
);
이 경우,React는 Welcome component를 {name: ‘Sara’}라는 props을 넘겨 호출한다.
그 결과, Welcome component는 결과로 , <h1>Hello, Sara</h1> 라는 element를 return 한다.
React DOM는 해당 변경사항에 해당하는 DOM 부분만 update 한다.
Composing Components
컴포넌트는 다른 컴포넌트를 그들의 output에 사용할 수 있다.
그 결과, 계층에 상관 없이, 동일한 컴포넌트 추상성을 사용할 수 있다.
button, form, dialog, screen 모두 React app에서는 component로 표현된다.
function Welcome(props) {
return <h1>Hello, {props.name}</h1>;
}
function App() {
return (
<div>
<Welcome name="Sara" />
<Welcome name="Cahal" />
<Welcome name="Edite" />
</div>
);
}
ReactDOM.render(
<App />,
document.getElementById('root')
);
App component는 Welcome을 여러번 render하고 있다.
Read-only Props
function withdraw(account, amount) {
account.total -= amount;
} //impure function
input으로 들어온 account를 변화시키고 있다.
그러나, 리액트는 엄격한 규칙이 하나 있다.
모든 리액트 컴포넌트는 pure function처럼 그들의 prop을 존중해야 한다.