React 상태 끌어올리기를 useState로 어떻게 구현할 수 있나요?
React에서 useState를 이용하여 변수를 관리하는데 일반적인 상태 끌어올리기는 공홈에도 설명이 잘 되어 있으나 useState를 이용한 상태 끌어올리기는 찾으려고해도 자료가 많지 않네요.
가장 기본의 예제를 작성해 주시면 참고하겠습니다.
또한 위 내용과 관련한 간단한 팁들도 주시면 감사하겠습니다.
55글자 더 채워주세요.
1개의 답변이 있어요!
- const scaleNames = { c: 'Celsius', f: 'Fahrenheit' }; 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(); } function BoilingVerdict(props) { if (props.celsius >= 100) { return <p>The water would boil.</p>; } return <p>The water would not boil.</p>; } 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> ); } } 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> ); } }
이게 setState를 사용하는 예시인데요,
const scaleNames = { c: "Celsius", f: "Fahrenheit" }; 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(); } function BoilingVerdict(props) { if (props.celsius >= 100) { return <p>The water would boil.</p>; } return <p>The water would not boil.</p>; } function TemperatureInput({ onTemperatureChange, temperature, scale }) { const handleChange = useCallback( e => { onTemperatureChange(e.target.value); }, [onTemperatureChange] ); return ( <fieldset> <legend>Enter temperature in {scaleNames[scale]}:</legend> <input value={temperature} onChange={handleChange} /> </fieldset> ); } function Calculator() { const [{ temperature, scale }, setState] = useState({ temperature: "", scale: "" }); const handleCelsiusChange = useCallback(temperature => { setState({ scale: "c", temperature }); }, []); const handleFahrenheitChange = useCallback(temperature => { setState({ scale: "f", 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={handleCelsiusChange} /> <TemperatureInput scale="f" temperature={fahrenheit} onTemperatureChange={handleFahrenheitChange} /> <BoilingVerdict celsius={parseFloat(celsius)} /> </div> ); }특별한 건 없고, 단순히 클래스형 컴포넌트를 함수형 컴포넌트로 바꾸면 됩니다.