본문 바로가기
내마음대로만들어보자/React 프로젝트 만들기 이해

[React] 최소단위 컴포넌트 만들기 - Text

by 소농민! 2021. 10. 31.
728x90

* 기본뼈대코드 

import React from "react";

import styled from "styled-components";

 

const Text = (props) => {

 

       return (

         <React.Fragment>

 

         </React.Fragment>

       )

}

 

Text.defaultProps = {

  

}


export default Text;

1. 기본 스타일 잡기

Text.defaultProps = {

  children: null,

  bold: false,

  color: "#222831",

  size: "14px",

  margin: false,

};

* Text의 경우 children 속성을 이용해서 자식 계체를 가져오는게 자연스러워 보인다! 

 

2. 설정한 기본 스타일 props로 받아오기

 

const { bold, color, size, children, margin } = props;

 

3. Text 스타일 잡기

const P = styled.p`

color: ${(props) => props.color};

font-size: ${(props) => props.size};

font-weight: ${(props) => (props.bold? "600" : "400")};

// bold가 true : 600 , false : 400

${(props) => (props.margin? `margin: ${props.margin};` : '')}

`;

 

4. Text 스타일 적용 및 리턴해주기

const styles = {bold: bold, color: color, size: size, margin};

 

return (

<P {...styles}>

{children}

</P>

)

 

 

5. Text.js 적용하기 (Post.js)

<Grid is_flex width="auto">

  <Image shape="circle" src={props.src} />

  <Text bold>{props.user_info.user_name}</Text>

</Grid>

<Grid is_flex width="auto">

<Text>{props.insert_dt}</Text>

</Grid>

<Grid padding="16px">

<Text>{props.contents}</Text>

</Grid>

<Grid padding="16px">

<Text margin="0px" bold>

댓글 {props.comment_cnt}개

</Text>

</Grid>

이런식으로, Image.js , Text.js 최소단위 컴포넌트(elements 폴더)를 만들어서 내가 만든 기획서내에 

필요한 부분에 적절하게 사용할 수 있다!

 

 

* import를 한번에 하는 방법

elements 폴더에 새로운 index.js를 만들어서 한번에 임포트를 해준다.

 

import Grid from "./Grid";

import Image from "./Image"

import Text from "./Text";

 

export {Grid, Image, Text};

 

이런식으로 새로운 파일을 만들어 준 뒤 Post.js에서는 한줄로 간단하게 import 할 수 있다.

 

import { Grid, Image, Text } from "../elements";