비전공자 개발일기

React 본문

React & React Native

React

HiroDaegu 2021. 8. 15. 09:47
728x90
SMALL

1. node.js 설치

2. create-react-app로 리액트 프로젝트 생성

 

3. npm init react-app <폴더이름> 또는 폴더를 VS Code로 열고 터미널에서 npm init react-app .

 

4. 개발모드 실행: npm run start

 

5. react 개발자 도구: chrome 확장프로그램 [react developer tools]

 


JSX: 자바스크립트의 확장 문법

import ReactDOM from 'react-dom';

ReactDOM.render(<h1>안녕 리액트!</h1>, document.getElementById('root'));
  • 속성명은 카멜 케이스로 작성 ex) onClick,,onBlur, onFocus, onMouseDown, onMouseOver, tabIndex
import ReactDOM from 'react-dom';

ReactDOM.render(
  <button onClick= ... >클릭!</button>,
  document.getElementById('root')
);

단, 예외적으로 HTML에서 비표준 속성을 다룰 때 활용하는 data-* 속성은 기존의 HTML 문법 그대로 작성

import ReactDOM from 'react-dom';

ReactDOM.render(
  <div>
    상태 변경: 
    <button className="btn" data-status="대기중">대기중</button>
    <button className="btn" data-status="진행중">진행중</button>
    <button className="btn" data-status="완료">완료</button>
  </div>,
  document.getElementById('root')
);
  • 자바스크립트 예약어와 같은 속성명은 사용 불가 ex) for(htmlFor로 사용), class(className으로 사용) 등
import ReactDOM from 'react-dom';

ReactDOM.render(
  <form>
    <label htmlFor="name">이름</label>
    <input id="name" className="name-input" type="text" />
  </form>,
  document.getElementById('root')
);
  • 반드시 하나의 요소로 감싸기 - Fragment
import { Fragment } from 'react';
import ReactDOM from 'react-dom';

ReactDOM.render(
  <Fragment>
    <p>안녕</p>
    <p>리액트!</p>
  </Fragment>,
  document.getElementById('root')
);


-------------------------------------------------------------------

import ReactDOM from 'react-dom';

ReactDOM.render(
  <>
    <p>안녕</p>
    <p>리액트!</p>
  </>,
  document.getElementById('root')
);
  • 자바스크립트 표현식 넣기 -> 중괄호 {} 단, 중괄호 안에서 for, if 문 등은 불가
import ReactDOM from 'react-dom';

const product = 'MacBook';
const model = 'Air';
const imageUrl = 'https://upload.wikimedia.org/wikipedia/commons/thumb/1/1e/MacBook_with_Retina_Display.png/500px-MacBook_with_Retina_Display.png'

function handleClick(e) {
  alert('곧 도착합니다!');
}

ReactDOM.render(
  <>
    <h1>{product + ' ' + model} 주문하기</h1>
    <img src={imageUrl} alt="제품 사진" />
    <button onClick={handleClick}>확인</button>
  </>,
  document.getElementById('root')
);

리액트 엘리먼트

import ReactDOM from 'react-dom';

const element = <h1>Hello!</h1>;
console.log(element);   // {$$typeof: Symbol(react.element), type: "h1", key: null, ref: null, props: {…}, …}
ReactDOM.render(element, document.getElementById('root'));

JSX 문법으로 작성한 요소 = 자바스크립트 객체 -> 이러한 성질의 객체 = 리액트 엘리먼트


리액트 컴포넌트

import ReactDOM from 'react-dom';

function Hello() {
	return <h1> Hello!!! </h1>;
}

const element = (
<>
	<Hello/>
    <Hello/>
</>    
);

ReactDOM.render(element, document.getElementById('root'));

리액트 컴포넌트의 이름은 반드시 첫글자 = 대문자


Props

  • JSX에서 컴포넌트를 작성할 때 컴포넌트에도 속성 지정 가능 -> Props(Properties)
  • 각 속성이 하나의 객체로 모여서 컴포넌트를 정의한 함수의 첫번째 파라미터로 전달됨
// App.js
import Dice from './Dice';

function App() {
  return (
    <div>
      <Dice color="red" num={2} />
    </div>
  );
}

export default App;

export default App;

//Dice.js
import diceBlue01 from './assets/dice-blue-1.svg';
import diceBlue02 from './assets/dice-blue-2.svg';
// ...
import diceRed01 from './assets/dice-red-1.svg';
import diceRed02 from './assets/dice-red-2.svg';
// ...

const DICE_IMAGES = {
  blue: [diceBlue01, diceBlue02],
  red: [diceRed01, diceRed02],
};

function Dice({ color = 'blue', num = 1 }) {
  const src = DICE_IMAGES[color][num - 1];
  const alt = `${color} ${num}`;
  return <img src={src} alt={alt} />;
}

export default Dice;

Children

  • JSX로 컴포넌트를 작성할 때 컴포넌트를 단일 태그가 아닌 <여는 태그>{children}</닫는태그>
// Button.js
function Button({ children }) {
  return <button>{children}</button>;
}

export default Button;

// App.js
import Button from './Button';
import Dice from './Dice';

function App() {
  return (
    <div>
      <div>
        <Button>던지기</Button>
        <Button>처음부터</Button>
      </div>
      <Dice color="red" num={2} />
    </div>
  );
}

export default App;

State

  • 상태가 바뀔 때마다 화면을 새롭게 그려내는 방식으로 동작
import { useState } from 'react';

// ...

  const [num, setNum] = useState(1);

// ...

-----------------------------------------------------------
import { useState } from 'react';
import Button from './Button';
import Dice from './Dice';

function App() {
  const [num, setNum] = useState(1);

  const handleRollClick = () => {
    setNum(3); // num state를 3으로 변경!
  };

  const handleClearClick = () => {
    setNum(1); // num state를 1로 변경!
  };

  return (
    <div>
      <Button onClick={handleRollClick}>던지기</Button>
      <Button onClick={handleClearClick}>처음부터</Button>
      <Dice color="red" num={num} />
    </div>
  );
}

export default App;
  • 참조형(배열, 객체) State
// ... 

  const [gameHistory, setGameHistory] = useState([]);

  const handleRollClick = () => {
    const nextNum = random(6);
    setGameHistory([...gameHistory, nextNum]); // state가 제대로 변경된다!
  };

// ...

디자인 적용

  • 이미지 불러오기
import diceImg from './assets/dice.png';

function Dice() {
  return <img src={diceImg} alt="주사위 이미지" />;
}

export default App;
  • 인라인 스타일
import diceImg from './assets/dice.png';

const style = {
  borderRadius: '50%',
  width: '120px',
  height: '120px',
};

function Dice() {
  return <img style={style} src={diceImg} alt="주사위 이미지" />;
}

export default App;
  • CSS 파일 불러오기
import diceImg from './assets/dice.png';
import './Dice.css';

function Dice() {
  return <img src={diceImg} alt="주사위 이미지" />;
}

export default App;
  • className
import diceImg from './assets/dice.png';
import './Dice.css';

function Dice({ className = '' }) {
  const classNames = `Dice ${className}`;
  return <img className={classNames} src={diceImg} alt="주사위 이미지" />;
}

export default App;

-> classname 라이브러리: npm install classnames

https://www.npmjs.com/package/classnames

 

classnames

A simple utility for conditionally joining classNames together

www.npmjs.com

import classNames from 'classnames';

function Button({ isPending, color, size, invert, children }) {
  return (
    <button
      className={classNames(
        'Button',
        isPending && 'pending',
        color,
        size,
        invert && 'invert',
      )}>
     { children }
   </button >
  );
}

export default Button;

React 배포하기

  1.  build하기: npm run build(개발된 프로젝트 빌드) -> npx serve build(빌드한 것 로컬에서 실행)
  2. AWS S3
728x90
LIST

'React & React Native' 카테고리의 다른 글

React Native - Hello World 출력 및 환경 설정  (0) 2022.01.09
React vs React Native  (0) 2021.12.28
mini blog with React  (0) 2021.12.26
React  (0) 2021.12.19
React - Basic  (0) 2021.09.20