STATE

유다송·2022년 8월 16일
0

React

목록 보기
2/14
post-thumbnail

state

  • 기본적으로 데이터가 저장되는 곳

React.js 에서 바뀐 내용을 출력하는 방법

<!DOCTYPE html>
<html>
    <body>
        <div id="root"></div>
    </body>
    
    <script src="https://unpkg.com/react@17.0.2/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script type="text/babel">
        const root = document.getElementById("root");
        let counter = 0;
        function countUp() {
            counter = counter + 1;
            render()
        }
        function render() {
            ReactDOM.render(<App />, root);
        }
        const App = () => (
            <div>
                <h3>
                    Total Clicks: {counter}
                </h3>
                <button onClick={countUp}>
                Click me
                </button>
            </div>
        );
        render();
    </script>
</html>
  • render 함수를 다시 호출해주면 새 Container 컴포넌트를 생성하는 것이 아니라 다시 호출하더라도 숫자부분의 html만 바뀜

React.js 자체에서 리렌더링까지 해주는 방법

  • 위에서 썼던 함수
let counter = 0;
function countUp() {
}

const data = React.useState(0);

는 같은 역할을 함 [0,f] 라는 배열 반환

function App() {
  const [counter, modifier] = React.useState(0);
  return ( 
      <div>
          <h3>Total Clicks: {counter}</h3>
          <button>Click me</button>
      </div>
  )
};
  • counter는 받아올 값이고 modifier는 값을 변경해줌
function App() {
    const [counter, setCounter] = React.useState(0)
    const onClick = () => {
        setCounter(counter + 1);
    };
    return ( 
        <div>
            <h3>Total Clicks: {counter}</h3>
            <button onClick={onClick}>Click me</button>
        </div>
    )
};
  • modifier는 값 앞에 set을 붙여서 사용

state 연습

<!DOCTYPE html>
<html>
    <body>
        <div id="root"></div>
    </body>
    
    <script src="https://unpkg.com/react@17.0.2/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script type="text/babel">
        const root = document.getElementById("root");
        function App() {
            const [minutes, setMinutes] = React.useState()
            const onChange = () => {
                setMinutes(event.target.value);
            }
            const reset = () => {
                setMinutes(0);
            }
            return ( 
                <div>
                    <div>
                        <h1 className="hi">Super converter</h1>
                        <label htmlFor="minutes">Minutes</label>
                        <input 
                        id="minutes" 
                        value={minutes} 
                        placeholder="Minutes" 
                        type="number"
                        onChange={onChange}
                        />
                        <h4>You want to convert {minutes}</h4>
                        <label htmlFor="hours">Hours</label>
                        <input 
                        id="hours"
                        value={Math.round(minutes / 60)}
                        placeholder="Hours" 
                        type="number" 
                        />
                    </div>
                    <button onClick={reset}>Reset</button>
                </div>
            )
        };
        ReactDOM.render(<App />, root);
    </script>
</html>
  1. const [minutes, setMinutes] = React.useState() 로 state를 만듦. => array [data, data를 수정하기 위한 함수]
  2. value={minutes} : input의 value를 어디서든 수정가능. input값을 외부에서도 수정해주기 위해서 필요함.
  3. onChange : data를 업데이트

state 하나 더 추가하기

<!DOCTYPE html>
<html>
    <body>
        <div id="root"></div>
    </body>
    
    <script src="https://unpkg.com/react@17.0.2/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script type="text/babel">
        const root = document.getElementById("root");
        function App() {
            const [amount, setAmount] = React.useState()
            const [inverted, setInverted] = React.useState(false)
            const onChange = () => {
                setAmount(event.target.value);
            }
            const reset = () => {
                setAmount(0);
            }
            const onFlip = () => {
                reset();
                setInverted((current) => !current);
            }
            return ( 
                <div>
                    <div>
                   		<h1 className="hi">Super converter</h1>
                        <label htmlFor="minutes">Minutes</label>
                        <input 
                        id="amount" 
                        value={inverted ? amount * 60 : amount} 
                        placeholder="Minutes" 
                        type="number"
                        onChange={onChange}
                        disabled={inverted}
                        />
                        <h4>You want to convert {amount}</h4>
                        <label htmlFor="hours">Hours</label>
                        <input 
                        id="hours"
                        value={inverted ? amount : Math.round(amount / 60)}
                        placeholder="Hours" 
                        type="number"
                        onChange={onChange}
                        disabled={!inverted}
                        />
                    </div>
                    <button onClick={reset}>Reset</button>
                    <button onClick={onFlip}>{inverted ? "Turn back" : "Invert"}</button>
                </div>
            )
        };
        ReactDOM.render(<App />, root);
    </script>
</html>

state 실습

<!DOCTYPE html>
<html>
    <body>
        <div id="root"></div>
    </body>
    
    <script src="https://unpkg.com/react@17.0.2/umd/react.production.min.js"></script>
    <script src="https://unpkg.com/react-dom@17.0.2/umd/react-dom.production.min.js"></script>
    <script src="https://unpkg.com/@babel/standalone/babel.min.js"></script>
    <script type="text/babel">
        const root = document.getElementById("root");
        function MinutesToHours() {
            const [amount, setAmount] = React.useState()
            const [inverted, setInverted] = React.useState(false)
            const onChange = () => {
                setAmount(event.target.value);
            }
            const reset = () => {
                setAmount(0);
            }
            const onFlip = () => {
                reset();
                setInverted((current) => !current);
            }
            return ( 
                <div>
                    <div>
                        <h3>Min to Hour</h3>
                        <label htmlFor="minutes">Minutes</label>
                        <input 
                        id="amount" 
                        value={inverted ? amount * 60 : amount} 
                        placeholder="Minutes" 
                        type="number"
                        onChange={onChange}
                        disabled={inverted}
                        />
                        <label htmlFor="hours">Hours</label>
                        <input 
                        id="hours"
                        value={inverted ? amount : Math.round(amount / 60)}
                        placeholder="Hours" 
                        type="number"
                        onChange={onChange}
                        disabled={!inverted}
                        />
                    </div>
                    <button onClick={reset}>Reset</button>
                    <button onClick={onFlip}>{inverted ? "Turn back" : "Invert"}</button>
                </div>
            )
        };
        function KmToMiles() {
            const [kmAmount, setKmAmount] = React.useState()
            const [inverted, setInverted] = React.useState(false)
            const onChange = () => {
                setKmAmount(event.target.value);
            }
            const reset = () => {
                setKmAmount(0);
            }
            const onFlip = () => {
                reset();
                setInverted((current) => !current);
            }
            return <div>
                        <div>
                            <h3>KM to M</h3>
                            <label htmlFor="km">Km</label>
                            <input
                            id="kmAmount"
                            value={inverted ? kmAmount * 1.6 : kmAmount}
                            placeholder="km"
                            type="number"
                            onChange={onChange}
                            disabled={inverted}
                            />
                            <label htmlFor="miles">Miles</label>
                            <input
                            id="miles"
                            value={inverted ? kmAmount : kmAmount * 0.62}
                            placeholder="Miles"
                            type="number"
                            onChange={onChange}
                            disabled={!inverted}
                            />
                        </div>
                        <button onClick={reset}>Reset</button>
                        <button onClick={onFlip}>{inverted ? "Turn back" : "Invert"}</button>
                    </div>

        }
        function App() {
            const[index, setIndex] = React.useState("0")
            const onSelect = (event) =>{
                setIndex(event.target.value)
            }
            return ( 
                <div>
                    <h1>Super Converter</h1>
                    <select value={index} onChange={onSelect}>
                        <option value="xx">Select your units</option>
                        <option value="0">Minutes & Hours</option>
                        <option value="1">Km & Miles</option>
                    </select>
                    <hr />
                    {index === "xx" ? "Please select your unit" : null}
                    {index === "0" ? <MinutesToHours /> : null}
                    {index === "1" ? <KmToMiles /> : null}
                </div>
            );
        };
        ReactDOM.render(<App />, root);
    </script>
</html>

0개의 댓글