정말 많이 쓰이는 API입니다. 컴포넌트가 DOM 위에 생성되는 상태에 따라 실행되는 메소드들입니다.

 

구성 요소에는 수명주기가 있습니다. 구성 요소는 인스턴스화, 마운트, 렌더링 및 업데이트, 마운트 해제 및 소멸됩니다. 라이프 사이클은 단순하고 일관된 추상화 계층을 제공하여 브라우저 API의 복잡성을 관리하는 데 도움이됩니다. 라이프 사이클을 사용하면 렌더링을보다 세밀하게 제어하기 위해 각 단계에서 사용자 지정 코드를 선택적으로 실행할 수도 있습니다.

구성 요소 수명주기의 각 단계를 살펴 보겠습니다.

 

Mounting Cycle

 

constructor(object props)

 

컴포넌트 클래스가 인스턴스화됩니다. 생성자에 대한 매개 변수 는 부모 요소에 의해 지정된대로 요소의 initial 입니다. 

선택적으로 객체를에 할당하여 요소의 초기 상태를 지정할 수 있습니다 . 

현재이 요소에 대해 기본 UI가 렌더링되지 않았습니다. propsthis.state

 

componentWillMount()

이 메소드는 렌더링이 처음으로 발생하기 전에 한 번만 호출됩니다. 현재이 요소에 대해 렌더링 된 기본 UI는 없습니다.

 

render() -> React Element

render 메소드는 렌더링하기 위해 React Element를 반환해야합니다 (또는 아무것도 렌더링하지 않으려면 null).

 

componentDidMount()

이 메소드는 렌더링이 처음 발생한 후 한 번만 호출됩니다. 이제이 요소의 기본 UI가 렌더링을 마치고 직접 조작하기 위해 액세스 할 수 있습니다 . 를 사용하여 비동기 API 호출을하거나 지연된 코드를 실행 해야하는 경우 일반적으로이 방법으로 수행해야합니다.this.refssetTimeout

Updating Cycle

componentWillReceiveProps(object nextProps)

이 구성 요소의 부모가 새로운 세트를 전달했습니다 . 이 구성 요소는 다시 렌더링됩니다. 

메소드가 호출 되기 전에 선택적 으로이 컴포넌트의 내부 상태를 업데이트하기 위해 호출  수 있습니다 .propsthis.setState()render

 

shouldComponentUpdate(object nextProps, object nextState) -> boolean

 의 다음 값을 기반으로 구성 요소는 다시 렌더링하거나 다시 렌더링하지 않을 수 있습니다. 이 메소드의 기본 클래스 구현은 항상 리턴합니다 (구성 요소  다시 렌더링 해야 함 ). 최적화의 경우,이 메소드를 오버라이드 (override) 중 여부를 확인 또는 수정 된, 예를 들어, 이러한 객체에있는 각각의 키 / 값의 평등 테스트를 실행합니다. 리턴 하면 메소드가 호출되지 않습니다.props state true props state false render

 

componentWillUpdate(object nextProps, object nextState)

이 메소드는 다시 렌더링하기로 결정한 후에 호출됩니다. 업데이트가 이미 진행 중이므로 여기에 전화하지 않을 수 있습니다 .this.setState()

 

render() -> React Element

이 메소드는 return을 가정하여 호출 됩니다. render 메소드는 렌더링하기 위해 React Element를 반환해야합니다 (또는 아무것도 렌더링하지 않으려면 null).shouldComponentUpdatetrue

 

componentDidUpdate(object prevProps, object prevState)

이 메소드는 다시 렌더링이 발생한 후에 호출됩니다. 이 시점에서이 컴포넌트의 기본 UI가 메소드 에서 리턴 된 React 요소를 반영하도록 업데이트되었습니다 .render()

 

이글은 http://www.react.express/lifecycle_api 에서 참조한 글입니다. React를 시작하기에 앞서 기본중 기본으로 잘 외워둡시당

'React' 카테고리의 다른 글

React Library 모음  (0) 2019.09.05
React는 알고 코딩해야지 !  (0) 2019.09.04
React의 react-moment library 를 사용해보자  (0) 2019.08.21
템플릿 리터럴 이란 ?!  (0) 2019.08.20
React Styled Component  (0) 2019.08.19

https://www.npmjs.com/package/react-moment

 

moment

Parse, validate, manipulate, and display dates

www.npmjs.com

react-moment 는 날짜 관련 작업을 위한 js 라이브러리입니다 !

예제로는 

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            const dateToFormat = '1976-04-19T12:59-0500';
            <Moment>{dateToFormat}</Moment>
        );
    }
}

 

이런식으로 Moment를 사용해주면 Outputs 값으로

<time>Mon Apr 19 1976 12:59:00 GMT-0500</time>

이렇게 나옵니다.

 

자식이 아닌 속성을 사용하여 날짜를 전달하려는 경우 위의 예제를 이런 식으로 작성할 수도 있습니다.

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            const dateToFormat = '1976-04-19T12:59-0500';
            <Moment date={dateToFormat} />
        );
    }
}

 

날짜 값은 문자열, 객체, 배열 또는 Date인스턴스 일 수 있습니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            const dateToFormat = new Date('1976-04-19T12:59-0500');
            <Moment date={dateToFormat} />
        );
    }
}

 

 

moment는 기본적으로 시간은 60 초 (60000 밀리 초)마다 업데이트됩니다. interval소품을 사용하여 업데이트를 변경하거나 비활성화하십시오. 30 초 (30000 밀리 초)마다 시간을 업데이트합니다.

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment interval={30000}>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

Disables updating.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment interval={0}>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

Formatting

주어진 형식 문자열에 따라 날짜를 형식화합니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment format="YYYY/MM/DD">
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

Outputs

<time>1976/04/19</time>

 

Parsing Dates

parse = {string}

 

Moment는 대부분의 표준 날짜 형식을 구문 분석 할 수 있습니다. parse비표준 일 때 주어진 날짜를 구문 분석하는 방법을 순간적으로 알려주 려면 속성을 사용하십시오 .

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment parse="YYYY-MM-DD HH:mm">
                1976-04-19 12:59
            </Moment>
        );
    }
}

 

Add and Subtract

add={object}

subtract={object}

주어진 날짜에서 기간을 더하고 빼는 데 사용되며 기간은 객체 리터럴로 표시됩니다.\

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        const date = new Date();
 
        return (
            <div>
                <Moment add={{ hours: 12 }}>{date}</Moment>
                <Moment add={{ days: 1, hours: 12 }}>{date}</Moment>
                <Moment subtract={{ hours: 12 }}>{date}</Moment>
                <Moment subtract={{ days: 1, hours: 12 }}>{date}</Moment>
            </div>
        );
    }
}

 

From Now

때로는 timeago 또는 상대 시간이라고도하며 날짜 를 지금부터 시간으로 표시합니다 ( 예 : "5 분 전").

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment fromNow>1976-04-19T12:59-0500</Moment>
        );
    }
}

위와 아래 같은 코드 생략 가능

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment fromNow ago>1976-04-19T12:59-0500</Moment>
        );
    }
}

Outputs

<time>40 years ago</time>

 

From Now During

from = {string}

fromNowDuring  설정하면 fromNow  마찬가지로 상대 시간이 표시 되지만 해당 형식 이 사용 된 후에는 밀리 초 단위의 값만 표시 됩니다.

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment from="2015-04-19">1976-04-19T12:59-0500</Moment>
        );
    }
}

Outputs

<time>39 years</time>

 

To Now

 fromNow와 비슷하지만 반대 간격을 제공합니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment toNow>1976-04-19T12:59-0500</Moment>
        );
    }
}

Outputs:

<time>40 years ago</time>

To

to={String}

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment to="2015-04-19">1976-04-19T12:59-0500</Moment>
        );
    }
}

  Outputs:

<time>39 years</time>

 

Filter

filter={function}

렌더링 전에 날짜 값을 수정 / 변환하는 기능입니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        const toUpperCaseFilter = (d) => {
            return d.toUpperCase();
        };
 
        return (
            const dateToFormat = '1976-04-19T12:59-0500';
            <Moment filter={toUpperCaseFilter}>{dateToFormat}</Moment>
        );
    }
}

 

Outputs:

<time>MON APR 19 1976 12:59:00 GMT-0500</time>

 

With Title

withTitle={bool}

title완전한 날짜를 가진 요소에 속성을 추가합니다 .

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment format="D MMM YYYY" withTitle>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

Outputs:

<time title="1976-04-19T12:59-0500">19 Apr 1976</time>

 

Title Format

titleFormat={string}

속성을 title사용할 때 날짜의 형식을 지정 하는 방법 withTitle

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment titleFormat="D MMM YYYY" withTitle>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

Outputs:

<time title="19 Apr 1976">1976-04-19T12:59-0500</time>

Difference

diff={string}

decimal={bool}

unit={string}

 

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <div>
              <Moment diff="2015-04-19">1976-04-19T12:59-0500</Moment>
              <Moment diff="2015-04-19" unit="days">1976-04-19T12:59-0500</Moment>
              <Moment diff="2015-04-19" unit="years" decimal>1976-04-19T12:59-0500</Moment>
            </div>
        );
    }
}

 

Duration

duration={string}

date={string}

두 날짜 사이의 기간 (경과 시간)을 표시합니다. duration은 date 시간적으로 뒤에 있어야 합니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment duration="2018-11-1T10:59-0500"
                    date="2018-11-1T12:59-0500"
            />
        );
    }
}

 

Duration From Now

durationFromNow={bool}

현재 날짜와 제공된 날짜 시간 사이의 지속 시간 (경과 시간)을 표시합니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment date="2018-11-1T12:59-0500"
                    durationFromNow
            />
        );
    }
}

 

Unix Timestamps

unix={bool}

주어진 날짜 값을 유닉스 타임 스탬프로 구문 분석하도록 Moment에 지시합니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        const unixTimestamp = 198784740;
        return (
            <Moment unix>{unixTimestamp}</Moment>
        );
    }
}

Outputs:

<time>Mon Apr 19 1976 12:59:00 GMT-0500</time>

 

Local

local={bool}

현지 시간으로 결과를 출력합니다

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment local>
                2018-11-01T12:59-0500
            </Moment>
        );
    }
}

Outputs:

<time>Thu Nov 01 2018 18:59:00 GMT+0100</time> //현재시간

 

Timezone

tz={string}

시간대를 설정합니다. 서버 측 렌더링 (SSR)을 사용하려면 클라이언트와 서버가 공통 시간대를 기반으로 동일한 날짜 시간을 제공해야합니다.  tz속성은 공통 시간대 설정을 활성화합니다.

import React  from 'react';
import Moment from 'react-moment';
import 'moment-timezone';
 
export default class MyComponent extends React.Component {
    render() {
        const unixTimestamp = 198784740;
        return (
            <Moment unix tz="America/Los_Angeles">
                {unixTimestamp}
            </Moment>
        );
    }
}

Outputs:

<time>Mon Apr 19 1976 09:59:00 GMT-0800</time>

 

Calender

calendar={object|bool}

달력 기능에 사용되는 문자열을 사용자 정의하십시오.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        const calendarStrings = {
            lastDay : '[Yesterday at] LT',
            sameDay : '[Today at] LT',
            nextDay : '[Tomorrow at] LT',
            lastWeek : '[last] dddd [at] LT',
            nextWeek : 'dddd [at] LT',
            sameElse : 'L'
        };
 
        return (
            <Moment calendar={calendarStrings}>
                '1976-04-19T12:59-0500'
            </Moment>
        );
    }
}

Locale

locale = {string}

날짜를 표시하는 데 사용되는 Locale을 설정합니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        const dateToFormat = '1976-04-19T12:59-0500';
        return (
            <Moment locale="de">{dateToFormat}</Moment>
        );
    }
}

 

참고 경우에 따라 언어 파일이 순간적으로 자동으로로드되지 않고 수동으로로드해야합니다. 예를 들어 프랑스어 로캘을 사용하려면 부트 스트랩 (예 : index.js) 스크립트에 다음을 추가하십시오.

import 'moment/locale/fr';

 

Element

element={string|React.Component}

렌더링 할 요소 유형 (문자열 또는 함수)

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment element="span">1976-04-19T12:59-0500</Moment>
        );
    }
}

Outputs:

<span>Mon Apr 19 1976 12:59:00 GMT-0500</span>

OnChange

onChange={func}

onChange소품은 기본적으로 60 초마다 한 날짜가 업데이트 될 때마다 호출됩니다. 함수는 새로운 날짜 값을받습니다.

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment onChange={(val) => { console.log(val); }}>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

 

Other Props

다른 속성은 <time>요소에 전달됩니다 .

import React  from 'react';
import Moment from 'react-moment';
 
export default class MyComponent extends React.Component {
    render() {
        return (
            <Moment className="datetime" aria-hidden={true}>
                1976-04-19T12:59-0500
            </Moment>
        );
    }
}

 

Pooled Timer

기본적으로 마운트 된 각 <Moment />인스턴스 에 대해 타이머가 작성되어 날짜 값을 업데이트합니다. 이는 페이지에 인스턴스가 몇 개인 경우에 좋습니다. 그러나 마운트 된 인스턴스가 많은 경우 성능이 저하 될 수 있습니다. 풀링 된 타이머를 사용하여 문제를 해결합니다.

풀링 된 타이밍이 활성화되면 react-moment는 단일 타이머 만 사용하여 마운트 된 모든 <Moment />인스턴스 를 업데이트 합니다. 풀링 된 타이밍은 호출 startPooledTimer()하여 활성화되고을 호출 하여 중지됩니다 clearPooledTimer().

startPooledTimer()부트 스트랩 스크립트 (보통 index.js)에서 정적 메소드를 호출하여 타이머를 초기화하십시오

 

import React from 'react';
import ReactDOM from 'react-dom';
import Moment from 'react-moment';
import App from './components/app';
 
// Start the pooled timer which runs every 60 seconds
// (60000 milliseconds) by default.
Moment.startPooledTimer();
 
// Or set the update interval. This will update the mounted
// instances every 30 seconds.
// Moment.startPooledTimer(30000);
 
ReactDOM.render(<App />, document.getElementById('mount'));

 

이상으로 npm moment의 속성 값과 내용을 알아보았습니다.

npmjs.com에서 번역해온 글로 수정을 조금 했습니다. 감사합니다:)

'React' 카테고리의 다른 글

React는 알고 코딩해야지 !  (0) 2019.09.04
React Component LifeCycle API 이란?  (0) 2019.08.23
템플릿 리터럴 이란 ?!  (0) 2019.08.20
React Styled Component  (0) 2019.08.19
리액트의 인라인 스타일링 ! React Inline Styling  (0) 2019.08.19

ES6는 템플릿 리터럴(Template literal)이라고 불리는 새로운 문자열 표기법을 도입하였다. 템플릿 리터럴은 일반 문자열과 비슷해 보이지만, ‘ 또는 “ 같은 통상적인 따옴표 문자 대신 백틱(backtick) 문자 `를 사용한다.

 

const test = `템플릿 리터럴`;

일반적인 문자열에서 줄바꿈은 허용되지 않으며 공백(white-space)를 표현하기 위해서는 백슬래시(\)로 시작하는 이스케이프 시퀀스(Escape Sequence)를 사용하여야 한다. ES6 템플릿 리터럴은 일반적인 문자열과 달리 여러 줄에 걸쳐 문자열을 작성할 수 있으며 템플릿 리터럴 내의 모든 white-space는 있는 그대로 적용된다.

 

const test = `<div> hihi </div>`;

 

템플릿 리터럴은 + 연산자를 사용하지 않아도 간단한 방법으로 새로운 문자열을 삽입할 수 있는 기능을 제공한다. 이를 문자열 인터폴레이션(String Interpolation)이라 한다.

const firstName = 'Hong';
const LastName = 'gildong';

//ES 5
console.log('My nmae is ' + first + ' ' + second);

//ES 6
console.log(`My name is ${firstName} ${LastName}`);

문자열 인터폴레이션은 ${ … }으로 표현식을 감싼다. 문자열 인터폴레이션 내의 표현식은 문자열로 강제 타입 변환된다.

 

console.log(`1 + ` = ${1 + 1}`) 

// 1 + 1 = 2

 

참고 url : https://poiemaweb.com/es6-template-literals

최신 웹 앱을 스타일링하는 적절한 방법에 대해 많은 이야기가있었습니다. 문서 레벨에서 일반적이고 가장 오래된 스타일링 방법이 있습니다- style.css파일을 생성 하고 HTML 파일에서 링크하는 것이 더 최근에는 JS의 스타일링 방법입니다. 이것은 CSS-in-JS로 널리 알려져 있습니다.

CSS-in-JS는 CSS 모델을 문서 수준이 아닌 구성 요소 수준으로 추상화하는 스타일링 방식입니다. 이것은 CSS가 특정 구성 요소로만 범위가 지정 될 수 있고 문서 수준이 아니라는 개념입니다. CSS-in-JS를 사용하면 다음과 같은 이점이 있습니다.

  • HTTP 요청 수 감소 : CSS-in-JS는 자산과 리소스를로드하기 위해 HTTP 요청을하지 않아도됨을 의미합니다.
  • 스타일링 조각화 : CSS-in-JS를 사용하면 호환성 문제에 대한 걱정없이 자유롭게 스타일을 작성할 수 있습니다.

CSS-in-JS 접근법의 예는 styled-components 입니다. 스타일 구성 요소를 사용하면 클래스 이름 충돌에 대한 걱정없이 구성 요소에 일반 CSS를 작성할 수 있습니다. 단일 구성 요소로 범위가 지정되고 페이지의 다른 요소로 누출되지 않는 CSS를 작성하는 데 도움이됩니다.

스타일이 지정된 구성 요소 인 이유

스타일이 지정된 구성 요소를 사용하면 태그가 지정된 템플릿 리터럴을 사용하여 JavaScript로 CSS를 작성할 수 있습니다. 구성 요소와 스타일 간의 매핑을 제거합니다. 구성 요소는 하위 수준 스타일 구성으로 만들어집니다. 다음과 같은 이유로 스타일 구성 요소가 작성되었습니다.

  • 자동 중요 CSS : 스타일이 지정된 구성 요소는 페이지에 렌더링되는 구성 요소를 추적하고 해당 스타일을 완전히 자동으로 주입합니다. 코드 분할과 결합하면 사용자는 필요한 최소량의 코드를로드 할 수 있습니다.
  • 클래스 이름 버그 없음 : 스타일이 지정된 구성 요소는 스타일에 대한 고유 한 클래스 이름을 생성합니다. 중복, 겹침 또는 철자 오류에 대해 걱정할 필요가 없습니다.
  • CSS를 쉽게 삭제 : 클래스 이름이 코드베이스 어딘가에 사용되는지 알기가 어려울 수 있습니다. 스타일링 된 구성 요소는 모든 스타일링이 특정 구성 요소에 연결되어 있으므로 분명합니다. 컴포넌트가 사용되지 않고 (툴링이 감지 할 수있는) 삭제되면 모든 스타일이 컴포넌트와 함께 삭제됩니다.
  • 간단한 다이나믹 스타일링 : 소품 또는 글로벌 테마를 기반으로 컴포넌트의 스타일을 조정하는 것은 수십 개의 클래스를 수동으로 관리 할 필요없이 간단하고 직관적입니다.
  • 무통 유지 관리 : 구성 요소에 영향을 미치는 스타일을 찾기 위해 다른 파일을 찾아 다닐 필요가 없으므로 코드베이스의 크기에 상관없이 유지 관리가 매우 중요합니다.
  • 자동 공급 업체 접두사 : CSS를 현재 표준에 작성하고 Styled Components가 나머지를 처리하도록합니다.

일단 첫 번째로 

npm install --save styled-components

styled-components 를 install 해줍니다.

 

그런다음 

const Wrapper = styled.section`
  padding: 4em;
  background: papayawhip;
`;

render(
  <Wrapper>
    <Title>
      Hello World!
    </Title>
  </Wrapper>
);

 

이렇게 스타일을 줄 수 있습니다.

출력화면

이렇게 쉽게 스타일드 컴포넌트를 사용할 수 있습니다. 자주 쓰이고 유용합니다 !

+ Recent posts