React day02

suu1006·2022년 7월 31일
0

React

목록 보기
1/2

1. 클릭 시 alert로 내용이 뜬다.

import React from 'react';

const Test01 = () => {

    const test1 = () => {
        alert('test1')
    }
    const test2 = () => {
        alert('test2')
    }
    const test3 = (num) => {
        alert('num = ' + num)
    }
    const test4 = (num) => {
        alert(`num = ${num}`) // 백틱사용 
    }
    return (
        <div>
            <h2>이벤트 : on + 첫글자대문자</h2>
            <p>
                <button onClick = {test1}>클릭</button>
                <button onClick = {test2}>클릭</button>
            </p>
            <p>
                <button onClick = {() => {
                    console.log('사자')
                    console.log('호랑이')
                    console.log('기린')
                }}>클릭</button>
                <button onClick = {() => console.log('빨간 사과')}>클릭</button>
            </p>
            <button onClick = {() => test3(10)}>클릭</button>
            <button onClick = {() => test4(10)}>클릭</button>
        </div>
    );
};

export default Test01;

//리액트는 순수 자바스크립트가 아니다. => 베이스가 자바스크립트일 뿐이다.
// 함수 뒤에 ()를 붙이면 새로고침 하자마자 무조건 실행된다. 
// 해결하려면 함수로 한번 묶어준다.
// () => 함수(값) / 값을 넘길때는 화살표 함수를 꼭 써야한다.
// 훅스 = useState

> 결과

2. 신상명세서

import React from 'react';

const Test02 = () => {
    
    const title = '신상명세서'
    const arr = ['홍길동', '코난', '둘리']
    const data = [
        {id : 1, name : '동동이'},
        {id : 2, name : '짱구'},
        {id : 3, name : '도라에몽'}
    ]
    return (
        <div>
          <h2>{title}</h2>
          {/*  ul은 블럭단위!  */}
        {
            <ul style = {{border : '1px solid red'}}>
                {
                    /* map을 사용할땐 key를 잡아야한다. */
                    arr.map((item, index) => {
                        return (<li key = {index}> {index} / {item}</li>)
                    })
                }
            </ul>
        }
            <hr/>

            <ul sytle = {{border : '1px solid red'}}>
                {
                    data.map ((item, index) => 
                        <li key = {item.id}>{item.id} / {item.name}</li>)
                }
            </ul>
        </div>
    );
};

export default Test02;

> 결과

3. 이름 / 나이 / 색상 변경

import React, { useState } from 'react';

const Test03 = () => {
    
    const [name, setName] = useState('박정수')
    const[age, setAge] = useState(26)
    const [color, setColor] = useState('cyan')
    
    const onName = () => {
        setName('도라에몽')
    }
    const onAge = (num) => {
        setAge(num)
    }
    const onColor = () => {
        setColor('yellow')
    }

    return (
        <div>
           <h2 style = {{background : color}}>
                이름 : {name} / 나이 : {age}
           </h2>
           <p>
                <button onClick = {onName}> 도라에몽으로 이름 변경</button>
                <button onClick = {() => onAge(30)}>30살로 나이 변경</button> 
                <button onClick = {onColor}>yellow</button>
           </p>

        </div>
    );
};

export default Test03;

/*
hook이란? 
- hook은 리액트 16.버전에 추가되었다. 
- 클래스 컴포넌트를 작성하지 않아도 state와 같은 특징들을 사용할 수 있다. 
- 함수형 컴포넌트는 렌더링(새로 창이 열릴 때)마다 내부의 것들을 기억하지 못한다. 
- 다시 생성, 초기화 해야한다.(변수, 함수)

- 내부의 것들을 유지하기 위해서 hook을 사용한다. - usexxx

- useState 
값이 유동적으로 변할 때 
- const[상태데이터, 상태데이터 값을 변경해주는 함수] = React, useState (초기값)
*/

> 결과

4. 보이기 / 숨기기 / 토글(보이기/숨기기)

import React, { useState } from 'react';

const Test04 = () => {
    
    const [visible , setVisible] = useState('true')
    
    const onShow = () => {
        setVisible(true)
    }
    const onHide = () => {
        setVisible(false)
    }
    const onToggle = () => {
        setVisible(!visible)
    }
    
    return (
        <div>
            <button onClick = {onShow}> 보이기 </button>
            <button onClick = {onHide}> 숨기기</button>
            <button onClick = {onToggle} >{visible? '숨기기' : '보이기'}</button>
            <hr/>
            { 
                visible && <div style = {{width : 300, height : 300, margin : 20, background : 'hotpink' }}></div>
            }
        </div>
    );
};

export default Test04;

> 결과

5. 숫자 증가 / 감소 / 초기화

import React, { useState } from 'react';

const Test05 = () => {
    
    const [count, setCount] = useState(0)

    const onAdd = () => {
        setCount(count + 1)
    }

    const onSub = () => {
        setCount(count - 1)
    }
    const onReset = () => {
        setCount(0)
    }

    return (
        <div>
            <h2>숫자 : {count}</h2>
            <button onClick = {onAdd}>증가</button>
            <button onClick = {onSub}>감소</button>
            <button onClick = {onReset}>초기화</button>
        </div>
    );
};

export default Test05;

> 결과

6. 표 만들기

import React, { useState } from 'react';
import '../css/reset.css'

const Test06 = () => {
    const [data, setData] = useState([
        {seq: 1, name : '도라에몽', age : 20, addr : '서울', done : true},
        {seq: 2, name : '짱구', age : 19, addr : '부산', done : true},
        {seq: 3, name : '아리', age : 13, addr : '경기', done : false}

    ])
    return (
        <div>
            <table className = 'list'>
                <caption>신상명세서</caption>
                <colgroup>
                    <col className = "seq"/>
                    <col className = "name"/>
                    <col className = "age"/>
                    <col className = "addr"/>
                    <col className = "done"/>
                </colgroup>
                <thead>
                    <th>번호</th>
                    <th>이름</th>
                    <th>나이</th>
                    <th>주소</th>
                    <th>동의여부</th>
                </thead>
                <tbody>
                    {
                        data.map((item, index) => <tr key = {item.seq}>
                            <td>{item.seq}</td>
                            <td>{item.name}</td>
                            <td>{item.age}</td>
                            <td>{item.addr}</td>
                            <td>{item.done? '동의': '비동의'}</td>
                        </tr>)
                    }
                </tbody>
            </table>
        </div>
    );
};

export default Test06;

> 결과

0개의 댓글