본 게시글은 구름EDU 처음 만난 React 온라인강의를 시청한 후 학습한 정보를 기록하는 목적의 게시글입니다.
생각의 흐름에 따라 작성된 게시글입니다. 가독성이 떨어질 수 있습니다.
Shared State
> State에 있는 데이터를 여러개의 하위 컴포넌트에서 공유하여 사용하는 경우
> 하위 컴포넌트들이 각자 State에 데이터를 갖고 있을 필요가 없다
> 하위 컴포넌트의 state를 공통 상위 컴포넌트로 올려서 사용한다
{Project Name} / src / Chapter10 / TemperatureInput.js
import React from 'react';
const scaleNames = {
c: 'Celsuis',
f: 'Fahrenheit',
}
class TemperatureInput extends React.Component {
constructor(props){
super(props);
}
handleChange = (event) => {
this.props.onTemperatureChange(event.target.value);
}
render(){
const { scale, temperature } = this.props;
return (
<fieldset>
<legend>Enter temperature in {scaleNames[scale]}:</legend>
<input
value={temperature}
onChange={this.handleChange}/>
</fieldset>
)
}
}
export default TemperatureInput;
{Project Name} / src / Chapter10 / Calculator.js
import React from 'react';
import TemperatureInput from './TemperatureInput';
function BoilingVerdict(props){
if(props.celsius >= 100){
return <p>The water would boil.</p>
}
return <p>The water would not boil.</p>
}
function toCelsius(fahrenheit){
return (fahrenheit - 32) * 5 / 9;
}
function toFahrenheit(celsius){
return (celsius * 9 / 5) + 32;
}
function tryConvert(temperature, convert) {
const input = parseFloat(temperature);
if(Number.isNaN(input)) {
return '';
}
const output = convert(input);
const rounded = Math.round(output * 1000) / 1000;
return rounded.toString();
}
class Calulator extends React.Component {
constructor(props){
super(props);
this.state = {
scale: 'c',
temperature: '',
}
}
handleCelsiusChange = (temperature) => {
this.setState({scale: 'c', temperature: temperature});
}
handleFahrenheitChange = (temperature) => {
this.setState({scale: 'f', temperature: temperature});
}
render() {
const { scale, temperature } = this.state;
const celsius = scale === 'f' ? tryConvert(temperature, toCelsius) : temperature;
const fahrenheit = scale === 'c' ? tryConvert(temperature, toFahrenheit) : temperature;
return (
<div>
<TemperatureInput
scale = 'c'
temperature = {celsius}
onTemperatureChange = {this.handleCelsiusChange} />
<TemperatureInput
scale = 'f'
temperature = {fahrenheit}
onTemperatureChange = {this.handleFahrenheitChange} />
<BoilingVerdict
celsius={parseFloat(celsius)} />
</div>
)
}
}
export default Calulator;
{Project Name} / src / index.js
import React from 'react';
import ReactDOM from 'react-dom';
import './index.css';
import App from './App';
import reportWebVitals from './reportWebVitals';
import Calculator from './Chapter10/Calculator';
ReactDOM.render(
<Calculator/>,
document.getElementById('root')
);
reportWebVitals();
'오픈튜토리얼스 > 소플 : 처음 만난 React' 카테고리의 다른 글
[구름EDU|처음만난React#11] Composition vs Inheritance (0) | 2020.11.05 |
---|---|
[구름EDU|처음만난React#9] Forms (0) | 2020.11.03 |
[구름EDU|처음만난React#8] List and Key (0) | 2020.11.02 |
[구름EDU|처음만난React#7] Conditional Rendering (0) | 2020.11.01 |
[구름EDU|처음만난React#6] Handling Event (0) | 2020.10.31 |
최근댓글