hmk run dev

컴포넌트 쪼개기 + defaultProps 본문

React

컴포넌트 쪼개기 + defaultProps

hmk run dev 2021. 3. 29. 12:18

Grid.js

import React from "react";
import styled from "styled-components";

const Grid = (props) => {
  const { is_flex, width, margin, padding, bg, children } = props;
  const styles = {
    is_flex: is_flex,
    width: width,
    margin: margin,
    bg: bg,
    padding: padding, // 앞은 스타일명 뒤는 props로 받는 padding 값
  };
  return (
    <React.Fragment>
      {/* 위에서 props로 넘겨받은 값들은 styles로 오고  styles값은 아래의 스타일컴포넌트 안의 props형태로 정보를 전달해줘 이 컴포넌트 모양이 결정된다 */}
      <GridBox {...styles}>
        {/* 그리드 박스로 감싸고 이안에는 칠드런 으로 넘겨 받아야한다 */}
        {children}
      </GridBox>
    </React.Fragment>
  );
};

Grid.defaultProps = {
  //초기에 데이터가 없을때 이렇게 초기값을 설정
  children: null, // 없는 경우가 기본값
  is_flex: false,
  width: "100%",
  padding: false,
  margin: false,
  bg: false,
};

const GridBox = styled.div`
  width: ${(props) => props.width}; //props로 받아온 값을 그대로 받아온다
  height: 100%;
  box-sizing: border-box;
  ${(props) => (props.padding ? `padding : ${props.padding};` : "")}
  //패딩값은 있을 수도 없을 수도 있다 그러므로 props로 받아온 값이 있는지 확인후 있으면 그값을 패딩으로 없으면 빈칸으로
  ${(props) => (props.margin ? `margin:${props.margin};` : "")}
  ${(props) => (props.bg ? `background-color:${props.bg};` : "")}
  ${(props) =>
    props.is_flex
      ? `diplay: flex; align_items: center; justify-content: space-between;`
      : ""}
`;

export default Grid;

Post.js

import React from "react";
import Grid from "../elements/Grid";

const Post = (props) => {
  console.log(props);

  return (
    <React.Fragment>
      <Grid padding="16px">
        {/* 이 안의 것들이 모두 chilren으로 넘어간다 */}
        <div>user profile / user name / insert_dt</div>
        <div>contents</div>
        <div>image</div>
        <div>count cnt </div>
      </Grid>
    </React.Fragment>
  );
};

Post.defaultProps = {
  user_info: {
    user_name: "hmk",
    user_profile:
      "https://ww.namu.la/s/f5999e0e1f85ee971731e5079ba21b9d3bd254286ed57691c672535dab1298197594696b35d7653175f49166e943f052ebb07426d789b93ea8611b7461dcdeaf4b83e3cb4a7d784bace7619be82fcc2b167f440efdd09184f5ba8e03336ce678",

    //게시글 url
    image_url:
      "https://ww.namu.la/s/f5999e0e1f85ee971731e5079ba21b9d3bd254286ed57691c672535dab1298197594696b35d7653175f49166e943f052ebb07426d789b93ea8611b7461dcdeaf4b83e3cb4a7d784bace7619be82fcc2b167f440efdd09184f5ba8e03336ce678",
    contents: "화이팅!",
    comment_cnt: 10,
    insert_dt: "2021-02-27 10:00:00",
  },
};

export default Post;

'React' 카테고리의 다른 글

1 쿠키 저장 삭제  (0) 2021.04.01
파이어 베이스로 회원가입 기능 만들어주기  (0) 2021.03.29
무한스크롤  (0) 2021.03.29
자바스크립트 필수문법  (0) 2021.03.28
액션과 리듀서를 편하게 만들어주는 모듈  (0) 2021.03.26
Comments