TIL (today I learned)
TIL_2019-09-29 리액트 공부
grin-quokka
2019. 9. 29. 22:06
리액트 공부 : 인프런 생활코딩
-
컴포넌트로 구성
- 가독성, 재사용성, 유지보수가 좋다
- 파일을 수정할 때마다 자동으로 리로드 됨
npx create-react-app my-app
cd my-app
npm start
-
npx를 이용하면 잠깐 create-react-app을 설치하고 바로 지움 → 그래서 항상 최신버전
-
index.html에 있는
에 App.js 컴포넌트를 넣어 랜더링한다.
- ReactDOM.render(, document.getElementById('root'));
-
배포하는 방법
- npm run build → build라는 폴더가 생김 → 이 폴더 안에 있는 파일들을 배포해야한다.
- npx serve -s build 우리가 만든 build 폴더를 루트로 해서 server를 사용할 수 있다.
-
컴포넌트 만들기
-
jsx로 작성하면 알아서 바꿔준다.
-
가장 바깥쪽에는 하나의 최상위 태그만 있어야 한다.
-
컴포넌트 별로 하나의 파일로 만들어 준다.
import React, { Component } from 'react'; class App extends Component { render() { return ( Hello, React!! ); } } export default App;
-
-
props
-
a 태그에서 href라는 속성을 이용하듯이, 이렇게 사용하면 Subject라는 클래스 안에서 {this.pops.name} 으로 받아서 랜더링해준다.
-
경고 : Each child in a list should have a unique "key" props
→ 중복되지 않는 유니크한 키 값을 설정해주기
-
-
state
-
component가 실행될 때 render보다 constructor 함수가 먼저 실행되면서 초기화된다.
-
하위 component에 값을 주입시킬 수 있다.
-
props의 값이나 state 값이 바뀌면 render함수가 다시 호출되면서 화면에 다시 그려진다.
-
state 변경하기 this.setState({name:'HI'});
- [this.state.name](<http://this.state.name>) = 'HI'; 이런식으로 하면 안된다. 다시 랜더링되지 않는다.
- onClick 이벤트에 콜백 함수를 실행시켜 state를 변경한다면→ event.preventDefault( ); 그리고 this를 바인드해주기
-
-
React Developer Tools (크롬 확장 프로그램)
- https://tinyurl.com/yxkuyqrt
- 설치 후에 크롬 개발자 도구에서 React 탭을 클릭하면 원래 태그를 보여주고, 수정도 가능하다.
class App extends Component {
constructor(props) {
super(props);
this.state = { subject: {title:'HELLO'} }
}
render() {
return ();
}
}
import React, { Component } from 'react';
class App extends Component {
render() {
return (
Hello, React!!
);
}
}
export default App;