React - Base(4)

이예·2022년 10월 14일
0

React

목록 보기
4/21

이전의 코드에 변환 단위를 하나 더 추가하는 작업 진행

Km To Miles 추가

minutesTohours 변환인지 kmTomiles 변환인지 선택할 수 있게 select문 삽입하고 콘솔에 event값을 출력하여 옵션을 선택했을 때 값이 저장되는 변수를 찾음

    const [index, setIndex] = React.useState("0");
    const onSelect = (event) => {
        console.log(event)
    }
    return(
        <div>
            <h1 className="hi">Super Converter</h1>
            <select onChange={onSelect}>
                <option value="0">Minutes & Hours</option>
                <option value="1">Km & Miles</option>
            </select>

        </div>
    );

event.target의 value값에 선택된 옵션의 value가 들어있는 것을 확인

select에서 선택한 옵션의 value의 값(index의 값)이
"0"이면 minutesTohours 변환기 컴포넌트 나타나고
"1"이면 kmTomiles 변환기 컴포넌트가 나타다도록
삼항연산자를 사용하여 코드 작성
(디폴트값을 "xx"로 두어 선택하라는 메시지 표시)

    function App() {
        const [index, setIndex] = React.useState("xx");
        const onSelect = (event) => {
            setIndex(event.target.value)
        }
        return(
            <div>
                <h1 className="hi">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 units" : null}
                {index === "0" ? <MinutesToHours /> : null}
                {index === "1" ? <KmToMiles /> : null}
            </div>
        );
    }



profile
다 해보고싶은 사람

0개의 댓글