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함수에 인수 값을 넘겨주고 실행시키면 부모 컴포넌트에 해당 값이 전달이 된다.
[출처]
728x90
'JavaScript > React' 카테고리의 다른 글
참고하면 좋은 사이트 (0) | 2023.05.03 |
---|---|
React Router 경로가 변경되어도 React Redux connect 에 속한 render 는 호출되지 않는 다. (0) | 2023.05.03 |
[Spread Operator] 배열에 특정한 인덱스의 아이템 교체 (0) | 2023.05.03 |
React 보면 좋을 사이트 (0) | 2023.04.22 |