[React JS] #2. Props

4822 단어 react jsreact js

#2.1 Reusable Components with JSX + Props

1. Props

  • <Components props=”value” props={true}>
  • Ex)
import React from "react";

function Food({ fav }) {
  console.log();
  return <h1>I like {fav}</h1>;
}

function App() {
  return (
    <div>
      <h1>Hello</h1>
      <Food fav="kimchi" />
    </div>
  );
}

export default App;

#2.2 Dynamic Component Generation

1. Map

  • Function을 취해서 array의 각 item에 적용
  • Key를 전달해야 함. React 내부에서 사용
  • Ex)
Const friends = [“dal”, “mark”, “lynn”, “japan guy”]
Friensd.map(friend => {
	Return friend + “★”;
})

2. Dynamic Component

function Food({ name, picture }) {
  return (
    <div>
      <h1>I like {name}</h1>
      <img src={picture} />
    </div>
  );
}
  
const foodILike = [];

function renderFood(dish) {
  return <Food key={dish.id} name={dish.name} picture={dish.image} />;
}

function App() {
  return <div>{foodILike.map(renderFood)}</div>;
}

#2.3 Protection with PropTypes

1. Check props type

  • Props의 유무, 타입을 체크해야 함.
  • Props types 설치 (props가 원하는 props인지 check)
    Npm I prop-types
  • Code
import PropTypes from "prop-types";

Food.propTypes = {
  name: PropTypes.string.isRequired,
  picture: PropTypes.string.isRequired,
  rating: PropTypes.string.isRequired,
}

좋은 웹페이지 즐겨찾기