React

[React] props 사용하기

맑은 눈의 우사미 2023. 6. 22. 13:00
반응형

1. App.js

    import ProfileCard from "./ProfileCard";
    function App(){
        return(
            <div>
                <div>Personal Digital Assistance</div>
                <ProfileCard title = "Alexa" handle="@alexa123"/>
                <ProfileCard title = "Cortana" handle="@cortana32"/>
                <ProfileCard title = "Siri" handle="@siri01"/>
            </div>
        );
    }

    export default App;

src파일에 ProfileCard.js라는걸 만들었고

이 컴포넌트의 props로 title, handle정보를 넘겨줄 것이다

 

 

2. ProfileCard.js

    // function ProfileCard(props){ // 아래와 동일
        function ProfileCard({title, handle}){
        // const title = props.title;
        // const handle = props.handle;
        // const { title, handle } = props; // 100% equals with line3~4
        return (
            <div>            
                <div>Title is {title}</div>
                <div>Handle is {handle}</div>            
            </div>
        );
    }
    export default ProfileCard;

인자(argument)를 object로 받을 때 component에서 표시할 수 있는 방법이 몇 개 있는데,

function ProfileCard(props)와 같이 변수명으로 받아도 되지만 ProfileCard({ title, handle }) 로 표현할 수 있고 이 방법을 상당히 많이 쓴다고 한다. (사실 이건 jsx기능은 아니고 자바스크립트 기능이라고 함 ㅋ)

ㅇㅈ props.title, props.handle로 사용하는 것보다 훨씬 편하긴 함

반응형