Sass 사용시 node-sass 추가

$ yarn add node-sass

 

적용방법

 

src/MyComponent.js

import React from 'react';
import './MyComponent.scss';

const MyComponent = () => {
  return (
    <div className="MyComponent">
      <div className="something-inside">Hello CRA v2</div>
    </div>
  );
};

export default MyComponent;

 

src/MyComponent.scss

.MyComponent {
  background: black;
  color: white;
  padding: 1rem;
  .something-inside {
    background: white;
    color: black;
    font-size: 2rem;
    text-align: center;
    padding: 1rem;
  }
}

 

src/App.js

import React, { Component } from "react";
import MyComponent from "./MyComponent";

class App extends Component {
  render() {
    return (
      <div>
        <MyComponent />
      </div>
    );
  }
}

export default App;

 

 

CSS Module

 

CSS Module 은 사용 방식이 이전과 조금 다릅니다. 파일을 생성하실 때 파일이름.module.css 이런식으로 하시면 CSS Module 이 적용됩니다.

 

 

src/AnotherComponent.module.css

.wrapper {
  background: gray;
  color: white;
  padding: 1rem;
  font-size: 2rem;
}

 

src/AnotherComponent.js

import React from 'react';
import styles from './AnotherComponent.module.css';

const AnotherComponent = () => {
  return <div className={styles.wrapper}>What about CSS Module?</div>;
};

export default AnotherComponent;

 

src/App.js

import React, { Component } from 'react';
import MyComponent from './MyComponent';
import AnotherComponent from './AnotherComponent';

class App extends Component {
  render() {
    return (
      <div>
        <MyComponent />
        <AnotherComponent />
      </div>
    );
  }
}

export default App;

 

출처 : https://velog.io/@velopert/create-react-app-v2

'프로그래밍언어 > React' 카테고리의 다른 글

React Event 이벤트 종류  (0) 2019.07.20
React Component 불러오기 (props)  (0) 2019.07.20
React 주석  (0) 2019.07.20
React css사용방법  (0) 2019.07.20
React if문  (0) 2019.07.20

SyntheticEvent

This reference guide documents the SyntheticEvent wrapper that forms part of React’s Event System. See the Handling Events guide to learn more.

Overview

Your event handlers will be passed instances of SyntheticEvent, a cross-browser wrapper around the browser’s native event. It has the same interface as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.

If you find that you need the underlying browser event for some reason, simply use the nativeEvent attribute to get it. Every SyntheticEvent object has the following attributes:

boolean bubbles boolean cancelable DOMEventTarget currentTarget boolean defaultPrevented number eventPhase boolean isTrusted DOMEvent nativeEvent void preventDefault() boolean isDefaultPrevented() void stopPropagation() boolean isPropagationStopped() DOMEventTarget target number timeStamp string type

Note:

As of v0.14, returning false from an event handler will no longer stop event propagation. Instead, e.stopPropagation() or e.preventDefault() should be triggered manually, as appropriate.

Event Pooling

The SyntheticEvent is pooled. This means that the SyntheticEvent object will be reused and all properties will be nullified after the event callback has been invoked. This is for performance reasons. As such, you cannot access the event in an asynchronous way.

function onClick(event) { console.log(event); // => nullified object. console.log(event.type); // => "click" const eventType = event.type; // => "click" setTimeout(function() { console.log(event.type); // => null console.log(eventType); // => "click" }, 0); // Won't work. this.state.clickEvent will only contain null values. this.setState({clickEvent: event}); // You can still export event properties. this.setState({eventType: event.type}); }

Note:

If you want to access the event properties in an asynchronous way, you should call event.persist() on the event, which will remove the synthetic event from the pool and allow references to the event to be retained by user code.

Supported Events

React normalizes events so that they have consistent properties across different browsers.

The event handlers below are triggered by an event in the bubbling phase. To register an event handler for the capture phase, append Capture to the event name; for example, instead of using onClick, you would use onClickCapture to handle the click event in the capture phase.


Reference

Clipboard Events

Event names:

onCopy onCut onPaste

Properties:

DOMDataTransfer clipboardData


Composition Events

Event names:

onCompositionEnd onCompositionStart onCompositionUpdate

Properties:

string data


Keyboard Events

Event names:

onKeyDown onKeyPress onKeyUp

Properties:

boolean altKey number charCode boolean ctrlKey boolean getModifierState(key) string key number keyCode string locale number location boolean metaKey boolean repeat boolean shiftKey number which

The key property can take any of the values documented in the DOM Level 3 Events spec.


Focus Events

Event names:

onFocus onBlur

These focus events work on all elements in the React DOM, not just form elements.

Properties:

DOMEventTarget relatedTarget


Form Events

Event names:

onChange onInput onInvalid onSubmit

For more information about the onChange event, see Forms.


Mouse Events

Event names:

onClick onContextMenu onDoubleClick onDrag onDragEnd onDragEnter onDragExit onDragLeave onDragOver onDragStart onDrop onMouseDown onMouseEnter onMouseLeave onMouseMove onMouseOut onMouseOver onMouseUp

The onMouseEnter and onMouseLeave events propagate from the element being left to the one being entered instead of ordinary bubbling and do not have a capture phase.

Properties:

boolean altKey number button number buttons number clientX number clientY boolean ctrlKey boolean getModifierState(key) boolean metaKey number pageX number pageY DOMEventTarget relatedTarget number screenX number screenY boolean shiftKey


Pointer Events

Event names:

onPointerDown onPointerMove onPointerUp onPointerCancel onGotPointerCapture onLostPointerCapture onPointerEnter onPointerLeave onPointerOver onPointerOut

The onPointerEnter and onPointerLeave events propagate from the element being left to the one being entered instead of ordinary bubbling and do not have a capture phase.

Properties:

As defined in the W3 spec, pointer events extend Mouse Events with the following properties:

number pointerId number width number height number pressure number tangentialPressure number tiltX number tiltY number twist string pointerType boolean isPrimary

A note on cross-browser support:

Pointer events are not yet supported in every browser (at the time of writing this article, supported browsers include: Chrome, Firefox, Edge, and Internet Explorer). React deliberately does not polyfill support for other browsers because a standard-conform polyfill would significantly increase the bundle size of react-dom.

If your application requires pointer events, we recommend adding a third party pointer event polyfill.


Selection Events

Event names:

onSelect


Touch Events

Event names:

onTouchCancel onTouchEnd onTouchMove onTouchStart

Properties:

boolean altKey DOMTouchList changedTouches boolean ctrlKey boolean getModifierState(key) boolean metaKey boolean shiftKey DOMTouchList targetTouches DOMTouchList touches


UI Events

Event names:

onScroll

Properties:

number detail DOMAbstractView view


Wheel Events

Event names:

onWheel

Properties:

number deltaMode number deltaX number deltaY number deltaZ


Media Events

Event names:

onAbort onCanPlay onCanPlayThrough onDurationChange onEmptied onEncrypted onEnded onError onLoadedData onLoadedMetadata onLoadStart onPause onPlay onPlaying onProgress onRateChange onSeeked onSeeking onStalled onSuspend onTimeUpdate onVolumeChange onWaiting


Image Events

Event names:

onLoad onError


Animation Events

Event names:

onAnimationStart onAnimationEnd onAnimationIteration

Properties:

string animationName string pseudoElement float elapsedTime


Transition Events

Event names:

onTransitionEnd

Properties:

string propertyName string pseudoElement float elapsedTime


Other Events

Event names:

onToggle

Edit this page

 

reactjs/reactjs.org

The React documentation website. Contribute to reactjs/reactjs.org development by creating an account on GitHub.

github.com

https://reactjs.org/docs/events.html

'프로그래밍언어 > React' 카테고리의 다른 글

React Create-react-app V2 css , scss 변경사항 적용  (0) 2019.07.23
React Component 불러오기 (props)  (0) 2019.07.20
React 주석  (0) 2019.07.20
React css사용방법  (0) 2019.07.20
React if문  (0) 2019.07.20

MyComponent.js

 

import React, { Component } from 'react';

class MyComponent extends Component {
    render() {
        return (
            <div>
                나의 새롭고 멋진 컴포넌트
            </div>
        );
    }
}

export default MyComponent;

 

 

App.js

 

import MyComponent from './MyComponent';

1

 

import React , {Component} from 'react';
import './App.css'
import MyComponent from './MyComponent'; //MyCompopnent 파일 불러옵니다.

class App extends Component{
  render(){



    return(
<MyComponent/>
    )
  }
}

export default App;

 

 

import 를 이용하여 컴포넌트를 불러온다.

 

작동후 모습

 

 

Props

 

MyComponent.js (자식 컴포넌트)

            <div>
                안녕하세요 , 제이름은 {this.props.name} 입니다.
            </div>

 

App.js (부모 컴포넌트)

    return(
<MyComponent name="Petabyte"/>
    )

화면

 

 

defaultProps

 

class MyComponent extends Component {

    static defaultProps={
        name:'기본이름'
    }
    render() {
        return (
            <div>
                안녕하세요 , 제이름은 {this.props.name} 입니다.
            </div>
        );
    }
}

화면

 

 

PropTypes 종류

array : 배열

bool : 참, 거짓

func:함수

number:숫자

object:객체

string:문자열

symbol:ES6 문법의 심벌 개체

node :렌더링 할수 있는 모든것(숫자,문자열,element 또는 이들로 구성된 배열)

element:리액트 요소

instanseOf(myclass): 특정 클래스의 인스턴스

oneOf(['Male','Female']):주어진 배열 요소중 하나

oneOfType([React.PropTypes.string, React.PropTypes.number]):주어진 배열 안의 종류중 하나

arrayOf(React.PropTypes.number):주어진 종류로 구성된 배열

objectOf(React.PropTypes.number):주어진 종류의 값을 가진 객체

shape({name:React.PropTypes.striong, age:React.PropTypes.number}):주어진 스키마를 가진 객체

any:아무 종류

 

사용방법 : PropTypes.bool  또는 PropTypes.any.isRequired 같은 방식으로 사용

 

    constructor(props){
        super(props);
        this.state={
          number:0
        }

constructor 설정시 부모 컴포넌트에서 수정할수 없음.

'프로그래밍언어 > React' 카테고리의 다른 글

React Create-react-app V2 css , scss 변경사항 적용  (0) 2019.07.23
React Event 이벤트 종류  (0) 2019.07.20
React 주석  (0) 2019.07.20
React css사용방법  (0) 2019.07.20
React if문  (0) 2019.07.20
import React , {Component} from 'react';
import './App.css'

class App extends Component{
  render(){

    const style = {
      backgroundColor : 'gray',
      border:'1px solid black',
      height:Math.random(Math.random() * 500 ) + 50,
      width:Math.random(Math.random() * 500) + 50,
      WebkitTransition:'all',
      MozTransition:'all',
      msTransition:'all'
    };


    return(
      <div className="my-div"> 
      {/*요소 밖에서는 이렇게 주석 */}
        <h1>리액트 테스트</h1>
        <div style={style}
        // self-cloed 태그에서만 작동하는 주석
        />
        //이렇게는 주석이 되지않음.
        /*이것도 안됨*/
      </div>
    )
  }
}

export default App;

/> 안에 들어가야하며 새줄에 // 방식으로 주석을 사용할수있고. 그렇지 않을경우는

{/* 이런식으로 사용한다 */ }

화면에 보이는 모습

'프로그래밍언어 > React' 카테고리의 다른 글

React Event 이벤트 종류  (0) 2019.07.20
React Component 불러오기 (props)  (0) 2019.07.20
React css사용방법  (0) 2019.07.20
React if문  (0) 2019.07.20
React App.js  (0) 2019.07.20
import React , {Component} from 'react';


class App extends Component{
  render(){

    const style = {
      backgroundColor : 'gray',
      border:'1px solid black',
      height:Math.random(Math.random() * 500 ) + 50,
      width:Math.random(Math.random() * 500) + 50,
      WebkitTransition:'all',
      MozTransition:'all',
      msTransition:'all'
    };


    return(
      <div>
        <h1>리액트 테스트</h1>
        <div style={style}></div>
      </div>
    )
  }
}

export default App;

보이는 화면

 

 

Import 방식

App.css

.my-div{
  background-color: aqua;
  font-size: 15px;
}

 

 

App.js

import React , {Component} from 'react';
import './App.css'

class App extends Component{
  render(){

    const style = {
      backgroundColor : 'gray',
      border:'1px solid black',
      height:Math.random(Math.random() * 500 ) + 50,
      width:Math.random(Math.random() * 500) + 50,
      WebkitTransition:'all',
      MozTransition:'all',
      msTransition:'all'
    };


    return(
      <div className="my-div"> 
        <h1>리액트 테스트</h1>
        <div style={style}></div>
      </div>
    )
  }
}

export default App;

className 으로 div 를 설정한이후 App.css 를 import 한이후 사용한다.

 

설정시 보이는 화면

'프로그래밍언어 > React' 카테고리의 다른 글

React Component 불러오기 (props)  (0) 2019.07.20
React 주석  (0) 2019.07.20
React if문  (0) 2019.07.20
React App.js  (0) 2019.07.20
Create-react-app V2 변경 적용사항.  (0) 2019.07.13

ES6 의 const 와 let

 

var 방식

function myFunction(){
	var a = "hello";
    if(true){
    	var a = "bye";
        console.log(a);  // bye
       }
   console.log(a); //bye
 }
 
 

 

let 방식

function myFunction(){
	let a = 1;
    if(true){
    	let a = 2;
        console.log(a); // 2
    }
    console.log(a); //1
 }

 

const 는 재설정 불가.

 

 


If 문 대신 조건부 연산자.

 

import React , {Component} from 'react';


class App extends Component{
  render(){
    const text ='자바스크립트 테스트입니다.'
    const condition = true;


    return(
      <div>
        <h1>리액트 테스트</h1>
        <h2>{text}</h2> 
        {
          condition ? '참':'거짓'
        }
        <h5>참일때만 출력</h5>
        {
          condition ? '보여주세요':null
        }
        <h5>&& 연산자</h5>
        {
          condition  && '보여주세요'
        }
      </div>
    )
  }
}

export default App;

 

 

 

보이는 화면

 

'프로그래밍언어 > React' 카테고리의 다른 글

React 주석  (0) 2019.07.20
React css사용방법  (0) 2019.07.20
React App.js  (0) 2019.07.20
Create-react-app V2 변경 적용사항.  (0) 2019.07.13
React 초기 셋팅  (0) 2019.06.27
import React from 'react';
import logo from './logo.svg';
import './App.css';

function App() {
  return (
    <div className="App">
      <header className="App-header">
        <img src={logo} className="App-logo" alt="logo" />
        <p>
          Edit <code>src/App.js</code> and save to reload.
        </p>
        <a
          className="App-link"
          href="https://reactjs.org"
          target="_blank"
          rel="noopener noreferrer"
        >
          Learn React
        </a>
      </header>
    </div>
  );
}

export default App;

import React from 'react';  (ES6 방식)

 

npm 을 통해 설치하게되면 node_modules 에 설치가된다. 

그것을 불러와 사용하기 위하여 import 할때 사용한다.

 

 

자바스크립트로 해석하면 

var React = require('react');

 

ES6 class 문법

class Dog{
	constructor(name) {
    	this.name = name;
       }
    say(){
    	console.log(this.name + ': 멍멍');
       }
  }
  
  const dong = new Dog('휜둥이');
  dog.say();
  
  //휜둥이 : 멍멍

 

 

샘플로 설치된 리액트를 실행한 화면

 

'프로그래밍언어 > React' 카테고리의 다른 글

React 주석  (0) 2019.07.20
React css사용방법  (0) 2019.07.20
React if문  (0) 2019.07.20
Create-react-app V2 변경 적용사항.  (0) 2019.07.13
React 초기 셋팅  (0) 2019.06.27

 

index.js [serviceWorker]

import * as serviceWorker from './serviceWorker';

serviceWorker.register ();

 

 

webpack.config.js

            {
              test: sassRegex,
              exclude: sassModuleRegex,
              use: getStyleLoaders(
                {
                  importLoaders: 2,
                  sourceMap: isEnvProduction && shouldUseSourceMap,
                },
                'sass-loader'
              ),
              sideEffects: true,
            },

해당부분 아래와 같이 변경.

            {
              test: sassRegex,
              exclude: sassModuleRegex,
              use: getStyleLoaders({
                importLoaders: 2,
                sourceMap: isEnvProduction && shouldUseSourceMap
              }).concat({
                loader: require.resolve('sass-loader'),
                options: {
                  includePaths: [paths.appSrc + '/styles'],
                  sourceMap: isEnvProduction && shouldUseSourceMap
                }
              }),
              // Don't consider CSS imports dead code even if the
              // containing package claims to have no side effects.
              // Remove this when webpack adds a warning or an error for this.
              // See https://github.com/webpack/webpack/issues/6571
              sideEffects: true
            },

 

'프로그래밍언어 > React' 카테고리의 다른 글

React 주석  (0) 2019.07.20
React css사용방법  (0) 2019.07.20
React if문  (0) 2019.07.20
React App.js  (0) 2019.07.20
React 초기 셋팅  (0) 2019.06.27

node 설치 https://nodejs.org/ko/

 

Node.js

Node.js® is a JavaScript runtime built on Chrome's V8 JavaScript engine.

nodejs.org

yarn 다운로드 https://yarnpkg.com/en/docs/install#windows-stable

 

Yarn

Fast, reliable, and secure dependency management.

yarnpkg.com

yarn 설치 https://chocolatey.org/install

 

Installation

That's it! All you need is choco.exe (that you get from the installation scripts) and you are good to go! No Visual Studio required. Chocolatey installs in seconds. You are just a few steps from running choco right now! With PowerShell, there is an additio

chocolatey.org

 

Vscode 설치 https://code.visualstudio.com/

 

Visual Studio Code - Code Editing. Redefined

Visual Studio Code is a code editor redefined and optimized for building and debugging modern web and cloud applications.  Visual Studio Code is free and available on your favorite platform - Linux, macOS, and Windows.

code.visualstudio.com

VS Code 확장프로그램

ESLint (자바스크립트 문법체크)

Realative Path (상대경로 파일 경로 지정)

Guides (들여쓰기 가이드라인)

Reactjs code snippets (리액트관련 스니펫 모음) 제작사 : Charalampos Karypidis 

 

 

create-react-app 으로 TEST 

 

case1 yarn 설치
yarn global add create-react-app

case2 npm 설치  
npm install -g create-react-app

 

react 테스트

$ create-react-app hello-react
$ cd hello-react
$ yarn start

 

다음과 같은 화면이 나오면 초기 셋팅 완료.

'프로그래밍언어 > React' 카테고리의 다른 글

React 주석  (0) 2019.07.20
React css사용방법  (0) 2019.07.20
React if문  (0) 2019.07.20
React App.js  (0) 2019.07.20
Create-react-app V2 변경 적용사항.  (0) 2019.07.13

+ Recent posts