React

[React] Props

gaongg 2024. 10. 22. 10:20

📑Props?

  • Props(Property)란 상위 컴포넌트가 하위 컴포넌트에 값을 전달할 때 사용하는 속성
  • 상위 컴포넌트가 하위 컴포넌트에 값을 전달하기 때문에 단방향 데이터 흐름을 갖는다.

📍Props 타입

props의 자료형은 자바스크립트의 자료형을 모두 사용 가능하다. 

 

🔑 문자열 타입 프로퍼티 

-프로퍼티 타입이 문자열인 경우, 프로퍼티 값을 표현할 때는 큰 따옴표("")를 사용한다.

<Button name="버튼"/>

 

🔑 문자열 이외 타입의 프로퍼티 

-프로퍼티 타입 이외의 프로퍼티 값은 중괄호{}를 사용한다.

<Button 
	boolProp= {true} //boolean
	arrProp= {['a','b','c']} //배열
	objProp= {{name:'버튼', title:'버튼이야!'}} //객체
	funcProp= {() => { alert('알림창'); }}  //함수 
/>

 

📍Props 사용하기

1. 상위 컴포넌트에서 Props 지정하여 넘기기

  • 아래 코드에서 App 컴포넌트는 Button 컴포넌트를 포함하고 있으며 props 값을 지정해준다.
  • "text","color"라는 프로퍼티로 값을 넘겨주고 컴포넌트 태그 사이에 자식요소를 넣어준다.
import "./App.css";
import Button from "./components/Button";

function App() {
    return (
        <>
            <Button text={"메일"} color={"red"} />
            <Button text={"카페"} />
            <Button text={"블로그"}>
                <div>자식요소</div>
            </Button>
        </>
    );
}

export default App;

 

2. 하위 컴포넌트에서 Props 지정하여 넘기기

  • 상위 컴포넌트에서 받은 Props 데이터를 뷰에 렌더링해준다.
type ButtonProps = {
    text: string;
    color?: string;
    children?: React.ReactNode;
};

const Button = (props: ButtonProps) => {
    console.log(props);
    return (
        <button style={{ color: props.color }}>
            {props.text}-{props.color.toUpperCase()}
            {props.children}
        </button>
    );
};

export default Button;

 

  • 오류가 발생하진 않지만 color 값이 없는 버튼은 - 까지만 나오게 된다.
  • 예로 color값이 무조건 들어온다고 예상하고 대문자로 만들어 렌더링 시켜주기 위해 toUpperCase를 호출해 작성하면 아래와 같은 오류가 나온다! (2,3번째 버튼에는 color 값이 없기 때문)

  • 그래서 위와 같은 오류를 해결하기 위해 버튼 컴포넌트 color props의 기본값으로 black으로 설정해준다.
type ButtonProps = {
    text: string;
    color?: string;
    children?: React.ReactNode;
};

const Button = ({ text, color = "black", children }: ButtonProps) => {
    return (
        <button style={{ color: color }}>
            {text}-{color.toUpperCase()}
            {children}
        </button>
    );
};

// Button.defaultProps = {
//     color: "black",
// };

export default Button;

 

❗만약 부모에서 내려주는 props값이 많다! 하는 경우 아래와 같이 Object.assign으로 기본값을 지정할 수 있다고 한다

const Button = (props: ButtonProps) => {
    const { text, color, children } = Object.assign({ color: "black" }, ButtonProps);
    
    return (
        <button style={{ color }}>
            {text} - {color.toUpperCase()}
            {children}
        </button>
    );
};