본문 바로가기

JavaScript/React

부모에서 자식, 자식에서 부모로 Prop 전달하기

728x90

1. 부모에서 자식으로 Prop 전달하기

부모

import { Component } from 'react';

// 부모
class App extends Component {
    render (
        <div>
       	    <Searchbar text="Hi there!"/>
        </div>
    );
}

자식 - 클래스

import { Component } from 'react';
//자식

class Searchbar extends Component {
    render (
    	<div>
        	{this.props.text}
        <div>
    );
}

자식 - 함수

import React from 'react';

const Searchbar = (props) => {
    return (
    	<div>
        	{props.text}
        <div>
    );
}

2. 자식에서 부모로 Props 전달하기

부모

import { Component } from 'react';

class App extends Component {

    onSearchSubmit(text) {
    	console.log(text);
    }

    render (
    	<div>
       		<Searchbar onSubmit={this.onSearchSubmit}/>
        </div>
    );
}

자식

import { Component } from 'react';

class Searchbar extends Component {

    state = { text: '' };

    onFormSubmit = e => {
    	e.preventDefault();
        this.props.onSubmit(this.state.text);
    }

    render (
    	<div>
            <form onSubmit={this.onFormSubmit}>
       			<input 
            		value={this.state.text}
            		onChange={(e) => {this.setState({ text: e.tartget.value})}}/>
            </form>
        </div>
    );

}

먼저 부모 컴포넌트에서 함수로 onSearchSubmit을 prop 형태인 onSubmit 넘기고 자식 컴포넌트에서 onSubmit을 클릭했을 때마다 실행되는 함수인 onFormSubmit에서 props로 받은 onSubmit함수에 인수 값을 넘겨주고 실행시키면 부모 컴포넌트에 해당 값이 전달이 된다.

 

[출처]

https://mia-dahae.tistory.com/136

728x90