'리액트 기초'에 해당되는 글 1건

# 폴더 구조


class 방식으로 버튼 사용하기 


1. class 방식에 버튼 이벤트

// class 방식일 경우 
import React, { Component, PureComponent } from 'react';
// import React, {memo, useRef, useState} from 'react';


class btnTest extends Component {
    state = {
        text: 'state에서 text 알아보기',
        num: 0,
        inputVal : 'state input Val'
    };
    
    // input 사용할 때, 사용될 부분 
    input;
    onInputValChange = (e) => this.setState({ inputVal: e.target.value });
    onRefInput = (c) => {this.input = c;}
    // input 사용할 때, 사용될 부분 

     onNumBtn = (sign) => (e) => {
        if (sign === '+') {
            // setState에서는 값을 직접적으로 참조가 불가능함으로 함수로 리턴 형식으로 함.
            this.setState((pre) => {
                console.log(pre);
                return {
                    text: '증감',
                    num: pre.num + 1
                }
            });
        } else {
            this.setState((pre) => {
                console.log(pre);
                return {
                    text: '감소',
                    num: pre.num - 1
                }
            });
        }
    };

    render() {
        const { text, num ,inputVal } = this.state;
        return (
            <>
                <h2 id='test'>{text}</h2>
                <h2 id='num'>{num}</h2>
                <div>
                    <button onClick={this.onNumBtn('+')}>+</button>
                    <button onClick={this.onNumBtn('-')}>-</button>
                </div>
                <input type='text' value={inputVal} onChange={this.onInputValChange} ref={this.onRefInput}></input>
                <h1>{inputVal}</h1>
            </>
        );
    };
}
export default btnTest;

 

 

2. Hooks 방식에 버튼 이벤트

// class 방식일 경우 
// import React, { Component, PureComponent } from 'react';
import React, { memo, useEffect, useRef, useState } from 'react';

const btnTest = memo(() => {
    const [text, setText] = useState('Hooks Text Display');
    const [num, setNum] = useState(0);
    const [inputVal, setInputVal] = useState('input text');
    const input = useRef();

	const onNumBtn = (sign) => (e) => {
        if (sign === '+') {
            setText('증감');
            setNum((pre) => {
                return pre + 1;
            });
        } else {
            setText('감소');
            setNum((pre) => {
                return pre - 1;
            });
        }
    };

    const onInputValChange = (e) => {
        setInputVal(e.target.value);
    };

    return (
        <>
            <h2 id='test'>{text}</h2>
            <h2 id='num'>{num}</h2>
            <div>
                <button onClick={onNumBtn('+')}>+</button>
                <button onClick={onNumBtn('-')}>-</button>
            </div>
            <input type='text' value={inputVal} onChange={onInputValChange} ref={input}></input>
            <h1>{inputVal}</h1>
        </>
    );
});

export default btnTest;

3. client.jsx

import React from 'react';

// # https://ko.reactjs.org/docs/react-dom.html
// react-dom package는 앱의 최상위 레벨에서 사용할 수 있는 DOM에 특화된 메서드와 필요한 경우 React 모델 외부로 나갈 수 있는 해결책을 제공
// render(), hydrate(), unmountComponentAtNode(), findDOMNode(), createPortal()
// const ReactDom = require('react-dom');
import ReactDom from 'react-dom';

// # https://gist.github.com/velopert/21896de87566628b38b7ecb95973a7b3
// 코드가 변경되었을 때 페이지를 새로고침하지 않고 바뀐 부분만 빠르게 교체해주는 라이브러리
// const { hot } = require('react-hot-loader/root');
import { hot } from 'react-hot-loader/root';

// 불러올 컴포넌트의 이름
import btnTest from './component/btnTest';
const Hot = hot(btnTest);

ReactDom.render(<Hot />, document.querySelector('#root'));


 

 

4. webpack.config.js

const path = require('path');
const webpack = require('webpack');
// process.env.NODE_ENV = 'production';

module.exports = {
    // 프로젝트 이름 , 카멜 케이스는 안됨, 두 단어 이상을 사용한 프로젝트 이름 
    name: 'button-test', 
    mode: 'development', // 실서비스 : productuon
    // mode: 'productuon', // 실서비스 : productuon
    devtool: 'eval', // 빠르게
    resolve: {
        // 파일 형식 
        extensions: ['.js', '.jsx']
    },
    entry: {
        app: ['./client']
    }, // 입력
    module: {
        rules: [{
            test: /\.jsx?/,
            loader: 'babel-loader',
            options: {
                presets: [
                    ['@babel/preset-env', {
                        targets: {
                            browsers: ['> 5% in KR']
                        },
                        debug: true,
                    }],
                    '@babel/preset-react'],
                plugins: [
                    '@babel/plugin-syntax-class-properties',
                    "transform-class-properties",
                    'react-hot-loader/babel'
                ]
            }
        }]
    },
    plugins: [
        new webpack.LoaderOptionsPlugin({ debug: true }),
    ],
    output: {
        // webpack-dev-server에서 hot 로드 되기 위해서 위치 지정, 없을 경우 html에서 ./dist/app.js를 app.js로 변경해야함
        publicPath: '/dist/',
        path: path.join(__dirname, 'dist'),
        filename: 'app.js'
    }, // 출력
    devServer: {
        // contentBase: path.join(__dirname, "dist"),
        inline: true,
        hot: true,
        port: 9000,
        hot:true
    },

}

5. 전체소스코드 

 

# github.com/HelloPlutoKid/javascriptCodeTest/tree/master/12.react/0.react-pratice/2.function

 

HelloPlutoKid/javascriptCodeTest

Contribute to HelloPlutoKid/javascriptCodeTest development by creating an account on GitHub.

github.com

 

블로그 이미지

미나미나미

,