-
18/06/09 01_React 문법퍼블리싱/React.js 2018. 6. 11. 12:39
model, controller : spring, node => Redux
view: react
1. 형식 jsx
2. ajax => axios
3. 제어문
4. 이벤트
=============================================================
jsx => javascript + xml
1) script
<script type="text/javascript"> ES 5 버전
<script type="text/babel"> ES 6 버전
2) html 사용하고 XML 문법
1. 계층 구조
2. 여는 태그, 닫는 태그가 일치
3. 대소문자 구분
<br> <img src=""> => (X)
<br /> <img src="" /> => (O)
4. 반드시 최상위 태그가 필요하다. (중요)
<h1>안녕?</h1>
<p>반갑다</p> => (X)
<div>
<h1>안녕?</h1>
<p>반갑다</p>
</div> => (O)
=============================================================
트리형태의 가상메모리로 저장되어 있다가 render() 메소드가 실행되면 변경된 내용이 적용된다.
- 수정함과 동시에 적용된다 (페이지 새로고침없이 바로 적용됨.)
- 반복이 많거나 대용량일때 사용. ex) 인스타그램, 페이스북, 야후
- 속도가 빠름. 컴포넌트를 제작하기 때문에 재사용이 좋다. 낱개로 출력할 수 있다.(쪼갤수 있음.)
=============================================================
* 파일구조
public -> html, css,
src -> react 파일들
여러군데서 작업한 내용을 index.js에서 합쳐준다.
클래스 이름은 대문자로 시작하는게 좋다.
- 라이브러리를 추가할 때 src > package.json > dependencies 에 항목 추가 > 저장 > 오른쪽 하단 npm install 클릭
(** axios는 react에서 ajax임.)
* JSX는 자바스크립트로 변환되고 실행된다.
return (
<ol>
<li>면 위에 분말스프를 넣고,</li>
<li>끓는 물 260ml를 표시선까지 부어준 후,</li>
<li>뚜껑을 덮고 4분 후 맛있게 드시면 됩니다.</li>
</ol>
);위처럼 XML로 코딩하면 react lib가 아래처럼 변경해준다.
return (
//React.createElement(태그이름, 속성, 값)
React.createElement("ol", null,
React.createElement("li", null, "면 위에 분말스프를 넣고,"),
React.createElement("li", null, "끓는 물 260ml를 표시선까지 부어준 후,"),
React.createElement("li", null, "뚜껑을 덮고 4분 후 맛있게 드시면 됩니다.")
)
);*** ReactDOM
=> index.js 실행
=> ReactDOM.render(<App />, document.getElementById('root'));
===== XML => HTML로 변경후에 변경된 HTML을 root에 innerHTML
===== 새로고침, 변경내용 저장하면 => render() => 새로운 DOM을 만들어 준다.
===== 새로고침, 변경전에 가상으로 DOM을 제작
=========== 트리형태의 메모리로 저장(그래서 계층구조가 필요함.)
임시 저장 장소
react는 저장공간이 2개 > 저장 공간() =>
실제 저장 공간 () => 브라우저에 출력
*컴포넌트 제작
1) const Hello = function(){} =>기능이 한개
2) function Hello(){} => 위와 비슷
3) class Hello extends Component{} => 여러개 기능을 제작
4) const Hello = () => {} => arrow 함수 (람다식)
-문법
1) 속성을 넣을때 반드시 "" 사용
2) 외부 css 사용시 className
3) style 지정할때 변수를 만들어서 변수값을 대입
4) 계층 구조 : 반드시 전체를 포함하는 태그가 필요 ex) <a><b><c></c></b></a>
5) 대소문자를 구분
6) 클래스명, 함수명은 대문자로 함.
7) 클래스를 호출시에는 <클래스명 속성="" />
8) 값을 넣을때는 <tag>....{value}.....</tag>
9) return 안에 주석은 {/* 주석 */}
import React, {Component} from 'react';
class Hello2 extends Component{
render(){
const msg = "Hello";
const st={
fontFamily: '맑은 고딕',
color: 'green'
}
return (
<div style={st}>
<h1>{msg}</h1>
</div>
)
}
}
export default Hello2;* 예제 layout 만들기
Header.js
import React, {Component} from 'react';
class Header extends Component{
render(){
return <h1>Header</h1>
}
}
export default Header;Aside.js
import React, {Component} from 'react';
class Aside extends Component{
render(){
return <h1>부가정보</h1>
}
}
export default Aside;Content.js
import React, {Component} from 'react';
class Content extends Component{
render(){
const msg = "내용";
return <h1>{msg}</h1>
}
}
export default Content;Footer.js
import React, {Component} from 'react';
class Footer extends Component{
render(){
return <h1>Footer</h1>
}
}
export default Footer;Main.js
import React, {Component} from 'react';
import Menu from './Header';
import Aside from './Aside';
import Content from './Content';
import Footer from './Footer';
class Main extends Component{
render(){
return(
<table className="table">
<tr>
<td colSpan={2} align="center" height="100">
<Header />
</td>
</tr>
<tr>
<td align="center" width="200" height="500">
<Aside />
</td>
<td align="center" width="600" height="500">
<Content />
</td>
</tr>
<tr>
<td colSpan={2} align="center" height="100">
<Footer />
</td>
</tr>
</table>
)
}
}
export default Main;* 값 전송 하기
props : 컴포넌트에서 사용할 데이터 중 변동되지 않는 데이터를 다룰때 사용. (parent 컴포넌트에서 child 컴포넌트로 데이터를 전할 때..)
state : 컴포넌트에서 유동적인 데이터를 다룰 때 사용
특성 props state parent 컴포넌트에 의해 값이 변경 될 수 있는가? 예 아니오 컴포넌트 내부에서 변경 될 수 있는가? 아니오 예 (출처 : https://velopert.com/921)
-props
**속성값을 던지면 props를 통해 받는다.
index.js
ReactDOM.render(<App cates={cate} />, document.getElementById('root'));
App.js
class App extends Component {
//index.js 에서 보낸 속성값을 props로 받는다
constructor(props) //cates = [] 이 props로 들어왔당...
{
super(props);
}
render() {
// for 문, map으로 가져옴..
// const content = this.props.cates.map(function(cate){})
const content = this.props.cates.map((cate) =>
<div className="col-lg-4">
<div className="thumbnail">
<img src={cate.poster} width={"300"} height={"250"} className="img-rounded" />
<div className="caption">
<h4>{cate.title}</h4>
</div>
</div>
</div>
)
return (
<div className="row">
{content}
</div>
);
}
}
export default App;**여러개 속성을 던질 수 있다.
index.js
ReactDOM.render(<App movie={movie} rank={rank} box={box} reserve={reserve} />, document.getElementById('content'));
App.js
class App extends Component {
//props 속성값 받기
constructor(props)
{
super(props);
}
render() {
const movie = this.props.movie.map((m) =>
<td><img src={m.poster} width={"180"} height={"250"} title={m.title} /></td>
);
const rank = this.props.rank.map((m) =>
<tr>
<td>{m.rank}</td>
<td>{m.title}</td>
</tr>
);
const box = this.props.box.map((m) =>
<tr>
<td>{m.rank}</td>
<td>{m.title}</td>
</tr>
);
const reserve = this.props.reserve.map((m) =>
<tr>
<td>{m.rank}</td>
<td>{m.title}</td>
</tr>
);
return (
<div>
<div className={"row"}>
<table className={"table"}>
<tr>
{movie}
</tr>
</table>
</div>
<div className={"row"}>
<div className={"col-md-4"}>
<table className={"table table-hover"}>
<caption>영화 순위</caption>
<thead>
<tr className={"warning"}>
<th>순위</th>
<th>제목</th>
</tr>
</thead>
<tbody>
{rank}
</tbody>
</table>
</div>
<div className={"col-md-4"}>
<table className={"table table-hover"}>
<caption>박스오피스</caption>
<thead>
<tr className={"warning"}>
<th>순위</th>
<th>제목</th>
</tr>
</thead>
<tbody>
{box}
</tbody>
</table>
</div>
<div className={"col-md-4"}>
<table className={"table table-hover"}>
<caption>예매 순위</caption>
<thead>
<tr className={"warning"}>
<th>순위</th>
<th>제목</th>
</tr>
</thead>
<tbody>
{reserve}
</tbody>
</table>
</div>
</div>
</div>
);
}
}
export default App;(속성값을 한단계 아래로 전달 가능하나, 두단계 아래로는 불가능.. 따로함수가 있음.)
* 이벤트 처리
App.js
class App extends Component {
constructor(props)
{
super(props);
this.clickHandler = this.clickHandler.bind(this);
}
clickHandler(e)
{
alert("Hello Event");
}
render() {
// 위와 같음.
// const clickHandler = (e) => {
//
// }
/*
btn-sm btn-md btn-lg btn-xs
<scro[t>
function clickHandler()
{
}
</script>
<input type="button" value="" onClick="clickHandler" />
*/
return (
<div>
<input type={"button"} value={"클릭"} class={"btn btn-sm btn-primary"} onClick={this.clickHandler} />
</div>
);
}
}
export default App;App2.js
class App2 extends Component{
// 이벤트 등록 : 생성자에서 함
constructor(props)
{
super(props);
this.nameChangeHandler = this.nameChangeHandler.bind(this);
this.nameSubmit = this.nameSubmit.bind(this); //전송 버튼을 누를때
this.state = {value: ''};
}
// 이벤트 처리
nameSubmit(e)
{
alert("name: " + this.state.value);
}
nameChangeHandler(e)
{
// redux = front (MVC)
//alert("Name:" + e.target.value);
this.setState({value: e.target.value}); //값을 저장할때 쓰는 함수 ?? 값이 변경될 떄마다 저장
}
// 이벤트 발생 : render() 에서 함.
render()
{
return (
<div className="form-group">
<label className="control-label col-sm-2" htmlFor="name">name:</label>
<div className="col-sm-5">
<input type="text" className="form-control" placeholder="Enter Name" name="name" onChange={this.nameChangeHandler} />
</div>
<input type={"button"} value={"전송"} className={"btn btn-sm btn-success"} onClick={this.nameSubmit} />
</div>
)
}
}
export default App2;'퍼블리싱 > React.js' 카테고리의 다른 글
18/06/16 02_router 와 webpack (0) 2018.06.18 18/06/16 01_React 가상돔, state와 props (0) 2018.06.18 18/06/02 02_데이터 가져오기 (1) 2018.06.08 18/06/02 01_프로그램 설치 (0) 2018.06.07