React

React 기초

youngseokim_kr 2022. 1. 23. 19:51

Nodejs, VS Code 설치

npx create-react-app 파일 이름

app.js , index.js 파일 이용

npm run start.  -> 파일 실행해서 창 띄우기

npm i prop-types -> prop의 타입을 설정해줘서 오류를 방지할 수 있음

Button.prototype = {
  text: propTypes.string.isRequired,
};

text라는 prop는 string 타입이어야 하고 무조건 값이 있어야 한다.

string이 아닌 다른 타입을 넣어주면 경고문을 띄워준다.

css 파일은 각 모듈마다 css를 분리하여 만들어주고 그 페이지에 맞는 css를 import 해준다.

import propTypes from "prop-types";
import styled from "./Button.module.css";  //import css
 
function Button({ text }) {
  return <button className={styled.btn}>{text}</button>;
}

Button.prototype = {
  text: propTypes.string.isRequired,
};
export default Button;



//Button.module.css
.btn {
  color: white;
  background-color: tomato;
}

 

import { useEffect, useState } from "react";

function Hello() {
  function byFn() {
    console.log("bye:(");
  }
  function hiFn() {
    console.log("created :)");
    return byFn;
  }
  useEffect(hiFn, []);
  return <h1>Hello</h1>;
}

function App() {
  const [showing, setShowing] = useState(false);
  const onClick = () => setShowing((prev) => !prev);
  return (
    <div>
      {showing ? <Hello /> : null}
      <button onClick={onClick}>{showing ? "Hide" : "Show"} </button>
    </div>
  );
}

export default App;

생성될 때 없어질 때 실행하는 함수 만드는법