React 기본적인 문법
- 라이브러리/React js
- 2019. 8. 4. 23:52

1. React 기본 문법
import React, {Component} from "react";
class App extends Component{
render(){
return(
<div>Hello</div>
);
}
}
export default App
2. css 적용 방법
App.css
.App{
background: black;
color: aqua;
font-size: 36px;
padding: 1rem;
}
App.js
import React, {Component} from "react";
import "./App";
class App extends Component{
render(){
return(
<div className="App">Hello</div>
)
}
}
export default App;
3. 두개 이상의 코드 처리하는 방법
- 두개 이상의 엘리먼트는 무조건 하나의 엘리먼트로 감싸져있어야 한다.
import React, {Component, Fragment} from "react";
class App extends Component{
render(){
return(
<fragment>
<div>Hello1</div>
<div>Hello2</div>
</fragment>
)
}
}
export default App;
4. JSX 안에서 자바스크립트 값 사용하기
render(){
const name = 'React';
return(
<div>
name is {name}
</div>
)
}
5. props
- 부모 컴포넌트가 자식 컴포넌트에게 값을 전달할때 사용하며, 값을 변경할 수 없다. 즉, 읽기 전용이다.
MyName.js
import React, {Component} from "react";
class MyName extends Component{
render(){
return(
<div>
안녕하세요. 제 이름은 {this.props.name} 입니다.
</div>
)
}
}
MyName.defaultProps = {
name : "기본 이름"
}
export default MyName;
defaultProps는 아래 name을 빠트려먹을때 기본값으로 설정할 수 있다.
import MyName from './MyName.js';
render(){
return(
<MyName name="다한" />
)
}
export defualt App;
이렇게 단순히 이름 값만 가지고 올 때 함수형 컴포넌트를 사용할 수 있다. 더 간편한 문법으로 작성할 수 있다.
import React from "react";
const MyName = ({name}) =>{
return(
<div>
안녕하세요. 제 이름은 {name} 입니다.
</div>
)
}
export default MyName;
6. state
- props와는 다르게 자기 자신이 가지고 있다. 또, 내부에서 변경할 수 있다. 변경할 때에는 setState라는 함수로 사용한다.
App.js
import Counter from "./Counter";
render(){
return(
<Counter />
)
}
Counter.js
state = {
number : 0
}
handleAdd = () =>{
this.setState({
number : this.state.number +1
})
}
handleMin = () =>{
this.setState({
number : this.state.number -1
})
}
render(){
return(
<fragment>
<h1>카운터</h1>
<div>값 : {this.state.number}</div>
<button onclick={this.handleAdd}>+</button>
<button onclick={this.handleMin}>-</button>
</fragment>
)
}
export default Counter;
7. React 라이프사이클 API

컴포넌트 초기 생성
import React, {Component} from "react";
import MyComponent from "./MyComponent";
class App extends Component{
constructor(props){
super(props);
console.log('constructor');
}
componentDidMount(){
console.log('componentDidMount');
}
state = {
counter : 1
}
handleClick = () =>{
this.setState({
value : this.state.counter +1
})
}
render(){
return(
<div>
<h1>Hello React</h1>
{this.state.counter > 10 && <MyComponent value={this.state.counter} />} //대문자로 시작해야한다.
<button onclick={this.handleClick}>Click me</button>
</div>
)
}
}
export default App;
console 결과
constructor
componentDidMount
constructor() 함수 : 컴포넌트 생성자 함수, 컴포넌트가 새로 만들 때마다 이 함수가 호출된다.
componentDidMount() 함수 : 외부 라이브러리 연동(D3, masonry 등), 컴포넌트에 필요한 데이터 요청(Ajax, GraphQL 등), DOM과 관련된 작업(스크롤 설정, 크기 읽어오기 등)할 때 쓸 수 있다.
컴포넌트 업데이트
MyComponent.js
import React, {Component} from "react";
class MyComponent extends Component{
state = {
value : 0
}
static getDrivedStateFromProps(nextProps, prevState){
if(prevState.value !== nextProps.value){
return{
value : nextProps.value
}
}
return null;
}
shouldComponentUpdate(nextProps, nextState){
if(nextProps >= 10){
return false;
}
return true;
}
componentDidUpdate(prevProps, prevState){
if(this.props.value !== prevProps.value){
console.log("props 값이 바뀌었다.", this.props.value);
}
}
componentWillUnmount(){
console.log("good bye");
}
render(){
return(
<div>
<p>props : {this.props.value}</p>
<p>state : {this.state.value}</p>
</div>
)
}
}
export default MyComponent;
화면 결과
Hello React
props : 1
state : 1
클릭할 때마다 1씩 증가한다. 10이 되었을 때 더이상 올라가지 않는다.(업데이트 중지)
console 결과(클릭할 때마다)
constructor
componentDidMount
props 값이 바뀌었다, 2
props 값이 바뀌었다, 3
...
good bye // props 값과 state 값이 사라짐
getDrivedStateFromProps(nextProps, prevState) 함수 : 이 함수는 16.3 버전에 새롭게 만들어진 라이프사이클API이다. props로 받아온 값을 static로 동기화 하는 작업을 해줘야 하는 경우에 사용된다.
shouldComponentUpdate(nextProps, nextState) 함수 : 컴포넌트를 최적화하는 작업에서 유용하게 사용할 수 있는 함수이다. return false하면 업데이트 하지 않으며, return true를 해야 업데이트가 진행된다. 즉, 업데이트를 막아줄수 있는 함수로 생각하면 된다.
getSnapshotBeforeUpdate(prevProps, prevState) 함수 : DOM에 변화가 일어나기 직전의 시점으로 되돌아갈 수 있는 함수이다. 자세한 내용은 이곳에서 확인할 수 있다.
componentDidUpdate() 함수 : 실제로 업데이트가 되고 난 다음에 호출되는 함수이다. 예를들어 위 코드를 보면 업데이트 이전의 값과 지금의 값을 비교해서 변경된 것이 있으면 특정한 무언가를 구현하도록 하는 것이다.
컴포넌트 제거
componentWillUnmount(){
console.log('good bye');
}
componentWillUnmount() 함수 : 컴포넌트가 종료되었을 때 보여주는 함수이다.
컴포넌트에 에러가 발생했을 때
MyComponent.js 에러 발생
render(){
return(
<div>
{this.props.a.b} // undefined 에러 발생
</div>
)
}
App.js
state = {
counter : 1,
error : false
}
componentDidCatch(error, info){
this.setState({
error : true
})
}
render(){
if(this.state.error){
return <div>에러가 발생했습니다.</div>
}
return()
}
componentDidCatch(error, info) 함수 : 에러가 발생할 때 어떻게 처리해야 할것인지를 설정할 수 있는 함수이다. error는 어떤 에러가 났는지 알려주는것이고 info는 어디서 발생했는지 알려준다. 이 함수를 사용하려면 에러가 발생할 수 있는 컴포넌트의 부모 컴포넌트에서 구현해줘야 한다. 즉, MyComponent의 부모인 App.js에서 구현해야 하는 것이다.
이 글을 공유하기