728x90
출처 : 생활코딩 react redux
0. 핵심
> 컴포넌트 속 컴포넌트 속.... 으로 컴포넌트가 쌓일경우 컴포넌트간 state 전달을 위한
코드량이 무수히 늘어난다.
1. App.css
div{
border:5px solid #764abc;
margin:10px;
color:#764abc;
padding:10px;
}
2. App.js
import './App.css';
import React, {Component} from 'react';
import { render } from '@testing-library/react';
import AddNumberRoot from "./components/AddNumberRoot";
import DisplayNumberRoot from "./components/DisplayNumberRoot"
class App extends Component {
state = {number:0}
render(){
return (
<div className="App">
<h1>Root</h1>
<AddNumberRoot onClick={function(size){
this.setState({number:this.state.number + size})
}.bind(this)}/>
<DisplayNumberRoot number={this.state.number}/>
</div>
);
}
}
---- 이하 컴포넌트는 src > components 폴더에 생성 ----
3. AddNumber.jsx
import React, {Component} from 'react';
export default class AddNumber extends Component{
state = {size:1}
render(){
return(
<div>
<h1>Add Number</h1>
<input type="button" value="+" onClick={function(){
this.props.onClick(this.state.size);
}.bind(this)}></input>
<input type="text" value={this.state.size} onChange={function(e){
this.setState({size: Number(e.target.value)});
}.bind(this)}></input>
</div>
)
}
}
4. AddNumberRoot.jsx
import React, {Component} from 'react';
import AddNumber from "../components/AddNumber"
export default class AddNumberRoot extends Component{
render(){
return (
<div>
<h1>Add Number root</h1>
<AddNumber onClick={function(size){
this.props.onClick(size);
}.bind(this)}></AddNumber>
</div>
)
}
}
5. DisplayNumber.jsx
import React, {Component} from 'react';
export default class DisplayNumber extends Component{
render(){
return (
<div>
<h1>Display Number</h1>
<input type="text" value={this.props.number} readOnly></input>
</div>
)
}
}
6. DisplayNumberRoot.jsx
import React, {Component} from 'react';
import DisplayNumber from "../components/DisplayNumber"
export default class DisplayNumberRoot extends Component{
render(){
return (
<div>
<h1>Display Number root</h1>
<DisplayNumber number={this.props.number}></DisplayNumber>
</div>
)
}
}
728x90
'Front-End > React' 카테고리의 다른 글
[react-redux] 3. redux 와 component 코드 분리 (0) | 2021.02.17 |
---|---|
[react-redux] 2. redux 도입 어플리케이션 (0) | 2021.02.17 |
[React] 12. React로 사고하기(마지막) (0) | 2021.02.03 |
[React] 11. 합성 vs 상속 (0) | 2021.02.03 |
[React] 10. 조건부 렌더링 (0) | 2021.02.03 |
댓글