본문 바로가기

프론트엔드/react

React (6) - Props

* Props: 부모 컴포넌트로부터 자식 컴포넌트에 데이터를 보낼 수 있게 해주는 방법

function MinutesToHours() {}
function KmToMies() {}
function App() {
<MinutesToHours />
<KmToMies /> }

 

위 코드를 보면 MinutesToHours 와 KmToMiles(자식 컴포넌트)들은 App(부모 컴포넌트)의 데이터를 필요로 하지 않는 독립적인 존재.

Props를 이용하여 부모 컴포넌트에서 자식 컴포넌트로 데이터를 보낼 수 있다.

컴포넌트를 효율적으로 사용할 수 있게 도와주는 Props

//예시 - 독립적인 컴포넌트

function SaveBtn() {
        return <button style={{
            backgroundColor: "tomato",
            color: "white",
            padding: "10px 20px",
            border: 0,
            borderRadius: 10
            
        }}> Save Changes </button>
    }

    function ConfirmBtn() {
        return <button style={{
            backgroundColor: "tomato",
            color: "white",
            padding: "10px 20px",
            border: 0,
            borderRadius: 10

        }}> Confirm </button>
    }

    function App() {
        return (
            <div>
                <SaveBtn />
                <ConfirmBtn />
            </div>
        )
    }

 

예를 들어, 동일한 스타일을 가진 버튼이 여러개 있을 때 독립적인 컴포넌트로 만들면 스타일을 컴포넌트마다 적용해야 하지만

Props를 활용하면 데이터를 전달해 text를 변경할 수 있다. 즉 버튼 컴포넌트 하나로만 동일한 스타일의 버튼을 여러개 생성할 수 있다.

 

    //props 활용
    
    function Btn({text, big}) {
        return <button style={{
            backgroundColor: "tomato",
            color: "white",
            padding: "10px 20px",
            border: 0,
            borderRadius: 10,
            fontSize: big ? 18 : 16
            
        }}> {text} </button>
    }

    function App() {
        return (
            <div>
                <Btn text="Save Changes" big={true}/>
                <Btn text="Continue" big={false}/>
            </div>
        )
    }

 

부모 컴포넌트에서 자식 컴포넌트로 데이터를 주는 방법은 <img src="">와 동일한 syntax 방법과 같다.

<Btn text="Save Change" />   =>  Btn({banana:"Save Change"}) 와 같이 Btn함수 첫번째 인자로 들어간다.

 

* shortcut  *

function Btn(props), {props.text}  = function Btn({text}), {text}

text는 props의 오브젝트 속 인자임을 알고 있기에 porps 대신 바로 text로 변경해도 된다.

 

반응형