(리액트) 상태 올리기

상태를 올리다

function A(){
   return(
      <>
        <B />
        <C />
      </>
   );
}

위의 구조화된 구성 요소가 존재한다고 가정해 보겠습니다.

만약에 C 컴포넌트~에 B 성분가지다 상태필요한 상황에서 가장 좋은 방법은 무엇입니까?


B 성분그리고 C 컴포넌트가지다 상태붓다 구성 요소골라서 사용하면 편리하지 않을까요?


그 때, 맞아 소품사용 상태교환할 수 있습니다.


섭씨 100도 또는 화씨 212도 이상이 되면 물이 끓고 있거나 물이 끓지 않는다는 메시지를 보여주기 위해 구현한 화면이다.

현재 섭씨와 화씨는 서로 다른 상태를 갖도록 구현됩니다.

동일한 기능은 다음과 같습니다.

  • 프롬프트에 숫자를 입력하세요.
  • 특정 기준을 초과하면 끓는 물 또는 끓지 않는 물이라는 메시지가 표시됩니다.
/**Calculator.js**/
import React from "react";
import BoilingVerdict from "./BoilingVerdict";
import TemperatureInput from "./TemperatureInput";

export default function Calculator() {
  return (
    <>
      <TemperatureInput scale={"c"} />
      <TemperatureInput scale={"f"} />
    </>
  );
}
/**BoilingVerdict.js**/

export default function BoilingVerdict(props) {
  // 섭씨
  if (props.scale === "c") {
    if (props.temperature >= 100) {
      return <p>The water would boil.</p>;
    }
    return <p>The water would not boil.</p>;
  }

  // 화씨
  if (props.temperature >= 212) {
    return <p>The water would boil.</p>;
  }
  return <p>The water would not boil.</p>;
}
/**TemperatureInput.js**/
import React, { useState } from "react";
import BoilingVerdict from "./BoilingVerdict";

const scaleNames = {
  c: "Celsius", // 섭씨
  f: "Fahrenheit", // 화씨
};

export default function TemperatureInput(props) {
  const (temperature, setTemperature) = useState(0);

  function handleChange(e) {
    setTemperature(e.target.value);
  }

  const scale = scaleNames(props.scale);

  return (
    <fieldset>
      <legend>Enter temperature in {scale}:</legend>
      <input value={temperature} onChange={handleChange} />
      <BoilingVerdict
        scale={props.scale}
        temperature={parseFloat(temperature)}
      />
    </fieldset>
  );
}

추가 기능 구현

  • 섭씨 <-> 화씨

온도 값을 섭씨/화씨로 입력하면 단위 환산으로 값을 표시하는 기능이 있습니다.

/**Calculator**/
const (state, setState) = useState({
     scale : "c",
     temperature : 0,
});

객체(obj)를 가져와서 그것이 어디에서 변했는지, 어떤 값(온도)을 가졌는지 알려주는 온도 변화 함수를 생성합니다.

const handleTemperatureChange = (obj) => {
   // 어디서수정했는지, 값(온도)는 무엇인지
   //obj.scale, obj.temperature
   setState({...state, scale:obj.scale, temperature : obj.temperature})
}

단위 환산 기능

  • 섭씨로
  • byFahrenheit
  //섭씨 변환
  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();
}

그런 다음 스케일 및 온도 변수를 상태에서 가져옵니다.

값이 삼항 연산자를 사용하여 각 변수와 일치하지 않으면 값을 반환하는 데 tryConvert가 사용됩니다.

const {scale, temperature} = state;

const celsius = scale === "f" ? tryConvert(tempertaure, toCelsius) : temperature
const fahrenheit = scale === "c" ? tryConvert(temperature, toFahrenheit) : temperature
return (
   <>
     <TemperatureInput scale={"c"} temperature={celsius} onTemperatureChange={handleTemperatureChange} />
     <TemperatureInput scale={"f"} temperature={fahrenheit} onTemperatureChange={handleTemperatureChange}/>
   </>
)

상태를 가져오는 Temperature.js를 변경하면 다음과 유사합니다.

/**TemperatureInput.js**/
import React, { useState } from "react";
import BoilingVerdict from "./BoilingVerdict";

const scaleNames = {
  c: "Celsius", // 섭씨
  f: "Fahrenheit", // 화씨
};

export default function TemperatureInput(props) {
  //const (temperature, setTemperature) = useState(0);

  function handleChange(e) {
    //setTemperature(e.target.value);
    props.onTemperatureChange({scale:props.scale, temperature:e.target.value});
  }

  const scale = scaleNames(props.scale);

  return (
    <fieldset>
      <legend>Enter temperature in {scale}:</legend>
      <input value={props.temperature} onChange={handleChange} />
      <BoilingVerdict
        scale={props.scale}
        temperature={parseFloat(props.temperature)}
      />
    </fieldset>
  );
}

Calculator 컴포넌트, 즉 최상위 컴포넌트에서 각 컴포넌트에 존재하는 상태를 관리하는 데 도움이 되었습니다.