리액트 기초 배우기 (React pt.1)

zenoan·2020년 10월 29일
1

독학

목록 보기
2/3
post-thumbnail

React setup

  1. terminal : npm install -g create-react-app

  2. create-react-app <파일이름>

  3. 또는 npx create-react-app 파일이름

  • React app start/stop (in terminal):
    start : cd 프로젝트 directory
    npm start (localhost:3000)
    stop : control + c
  • Babel : es 버전 --> es5. 브라우저들이 모든 es 버전을 지원하지 않기 때문.

Created Project files

프로젝트 directory

  • src : 소스코드 파일들이 들어가는 폴더
  • public : static 파일들 (예: 이미지 파일들) 들어가는 폴더
  • node_modules : 프로젝트 dependencies
  • package.json : dependecies 기록 / 설정
  • package-lock.json : 설치된 dependencies 기록
  • README.md

React

  • Component : function / class다. Component는 function / class 로 HTML을 만들어서 유저에게 컨텐츠를 보여주고(JSX), 유저의 피드백을 관리한다(event handler).
  • index.js:
import React from 'react';
import ReactDOM from 'react-dom';

// function component
const App = () => {
    return <div> Hello World! </div>;
}

// component to show on HTML
ReactDOM.render(
    <App />,
    document.querySelector('#root')
);

// class component
class App extends React.Component {
	render() {
        return <div> Hello World! </div>

ReactDOM.render(
    <App />,
    document.querySelector('#root')
);

JSX

  • HTML 구조와 유사한 javascript의 형식. 코딩하는 구조가 더 쉽고 알아보기 쉬움.
  • JSX vs HTML. jsx 코딩 형식은 html과 유사하지만 다름:
  1. styling 문법이 다르다
//html
<div style="background-color:red;"></div>
//jsx
<div style={{backgroundColor:'red'}}></div>
// 첫번째 {}는 javascript variable라는 것을 말하고, 안에 있는 두번째 {}는 javascript object라는 것을 말한다.
  • jsx 형식에서는 보통 "" 보다 '' 을 사용함
  1. jsx element 안에서는 class보다 className을 사용한다. React는 class component를 사용하기 때문이다. 예: class App extends react.Component {}
  2. jsx 에서는 javascript variables를 부를 수 있다.
const App = () => {
	const buttonText = "Click";
	return (
        <button style={{ backgroundColor: 'red' }}>
            {buttonText}
        <button>
    );
};
  • jsx에서는 javascript object를 부를 수 없다
const App = () => {
	const buttonText = {text: 'Click me'};
	return (
	    <button style={{backgroundColor: 'blue', color: 'white'}}>
			{buttonText}
        </button> // text: 'Click me' 를 호출 할 수 없음
    );
};
// buttonText 를 호출하기 위해:
<button style={{backgroundColor: 'blue', color: 'white'}}>
	{buttonText.text}
</button>

//또는
const App = () => {
	const buttonText = {text: 'Click me'};
	const style = {backgroundColor: 'red'};
	return (
		<button style={style}>
			{buttonText.text}
		</button>
    );
};

//property 중에 for 보다 htmlFor를 사용한다
<label className="label" for="name">
<label className="label" htmlFor="name">

Components

  • 사용법 :
// 새로운 js 파일을 생성, 이름은 생성하는 component의 기능을 기반으로 짓기. 예: CommentDetail.js 파일 생성
import React from "React";
import faker from "faker";

const CommentDetail = () => {
	return (
		<div className="comment">
			<a href="/" className="avatar">
				<img alt="avatar" src={faker.image.avatar()} />
			</a>
			<div className="contnet">
				<a href="/" className="author">
					Sam
				</a>
				<div className="metadata">
					<span className="date">TOday at 6:00PM</span>
				</div>
				<div className="text">Nice post!</div>
			</div>
		</div>
	);
};

// index.js 에서 호출가능하도록
export default CommentDetail;
//index.js 에서는
import React from "react";
import ReactDOM from "react-dom";
import faker from "faker";
import CommentDetail from "./CommentDetail";

const App = () => {
	return (
		<div className="ui container comments">
			<CommentDetail />
			<CommentDetail />
			<CommentDetail />
		</div>
	);
};

Props system

  • Parent component의 데이터를 child component로 보내주는 시스템.
//index.js (parent component)에서:
import React from "react";
import ReactDOM from "react-dom";
import faker from "faker";
import CommentDetail from "./CommentDetail";

const App = () => {
	return (
		<div className="ui container comments">
			<CommentDetail author="Sam" />
			<CommentDetail author="Alex" />
			<CommentDetail author="Jane" />
		</div> //author가 props
	);
};

//CommentDetail.js (child component)에서
import React from "React";
import faker from "faker";

// () 안에 props 입력
const CommentDetail = (props) => {
	return (
		<div className="comment">
			<a href="/" className="avatar">
				<img alt="avatar" src={faker.image.avatar()} />
			</a>
			<div className="contnet">
				<a href="/" className="author">
					{props.author}
				</a>
				<div className="metadata">
					<span className="date">TOday at 6:00PM</span>
				</div>
				<div className="text">Nice post!</div>
			</div>
		</div>
	);
};

export default CommentDetail;

Class component

  • JS의 class, extend React.Component, render method 정의
import React from "react";
import ReactDOM from "readct-dom";

// 내장 돼있는 React.Component class를 App class로 끌어온다는 뜻
class App extends React.Component {
	render() {
		window.navigator.geolocation.getCurrentPosition(
			(position) => console.log(position), //success callback
			(err) => console.log(err) //failure callback
		);
		return (
            <div>Latitude: </div>;
        );
	}
}

ReactDOM.render(<App />, document.querySelector("#root"));
profile
프론트엔드 개발자

1개의 댓글

comment-user-thumbnail
2020년 12월 28일

리액트 기초 독학은 도서로 진행하시나요?

답글 달기