리액트 기초

클래스형 컴포넌트

Posted by ETHAN KIM on April 01, 2022 · 5 mins read
React

주요 개념

  • Component / Props
  • 엘리먼트 조건부 렌더링 (State값 변화 감지)
  • 바벨을 통해 JSX 컴파일


실습 환경

  • nodejs react 패키지


테스트 결과 화면


최상위 Calculator Class

  • 최상위에서 temperature state 관리
  • state값 변화를 위한 함수 정의 및 부모객체와 이벤트 바인더링
  • 자식 Input Class에 전달
  • 자식 Class로부터 전달받은 state변경값을 감지하여 현재상태 출력
class Calculator extends React.Component {
  constructor(props){
    super(props);
    this.handleCelsiusChange = this.handleCelsiusChange.bind(this);
    this.handleFahrenheitChange = this.handleFahrenheitChange.bind(this);
    this.state = {temperature: '', scale: 'c'};
  }

  handleCelsiusChange(temperature){
    this.setState({scale: 'c', temperature});
  }

  handleFahrenheitChange(temperature){
    this.setState({scale: 'f', temperature});
  }

  render() {
    const scale = this.state.scale;
    const temperature = this.state.temperature;
    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>
    )
  }
}


Input 자식 Class

  • 부모 Class로부터 전달받은 함수를 onchange 이벤트에 연결
  • onchange 이벤트로 인한 리렌더링을 통해 전달받은 값을 input칸 내부 출력
class TemperatureInput extends React.Component{
  constructor(props){
    super(props);
    this.handleChange = this.handleChange.bind(this);
  }

  handleChange(e){
    this.props.onTemperatureChange(e.target.value);
  }

  render(){
    const temperature = this.props.temperature;
    const scale = this.props.scale;
    return(
      <fieldset>
        <legend>Enter temperature in {scaleNames[scale]}:</legend>
        <input value={temperature}
               onChange={this.handleChange} />
      </fieldset>
    );
  }
}


함수로직 / 변수

  • Calculator 객체에서 사용하기 위한 함수로직 및 변수
  • 전달받은 온도값을 화씨/섭씨 변경하여 렌더링 및 100도를 넘을 경우 상태값 변경
  • 전역에 선언되었으나 최상위 Class의 메소드로 선언하여도 됨
const scaleNames = {
  c : 'Celsius',
  f : 'Fahrenheit', 
};

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();
}