donaricano-btn

node.js를 이용한 react 컴포넌트 렌더링


1. 정의

-  Node.js 를 이용하여 HTML 을 생성한다


2. 폴더구성

- /node

    - email.js : react 컴포넌트

    - index.js : node.js 소스


3. index.js

1
2
3
4
5
6
7
8
9
10
11
const ReactDOMServer = require('react-dom/server')
const React = require('react')
const Email = React.createFactory(require('./email.js'))
 
const emailString = ReactDOMServer.renderToString(Email())
const emailStaticMarkup = ReactDOMServer.renderToStaticMarkup(Email())
console.log(emailString)
console.log(emailStaticMarkup)
 
const emailStringWithName = ReactDOMServer.renderToString(Email({name: 'Johny Pineappleseed'}))
console.log(emailStringWithName)

1) createFactory() : React 엘리먼트를 반환하는 함수를 생성한다. createElement() 로 대체할 수 있다

2) renderToStaticMarkup() : 브라우저 측의 React 를 위한 마크업이 필요치 않을 때 사용한다. renderToString() 과 비슷하지만 속성이 모두 제거되었다.

3) renderToString() : 브라우저 측의 React 를 위한 마크업이 필요할 때 사용한다. React 를 이용한 유니버셜 자바스크립트를 사용할 경우 필수도 사용된다.

4) Email({name:'Kyle'}) : 서버에서 속성을 이용하여 브라우저에 값을 전달 할 수 있다.

5) data-react-checksum 속성 : 서버 측 react 는 html에 체크섬 형식의 속성을 추가한다. 그리고 서버측의 체크섬 값과 비교하여 브라우저의 불필요한 재생성, 리페인트, 재렌더링을 피한다.


4. email.js

1
2
3
4
5
6
7
8
9
10
11
12
const React = require('react')
 
const Email = (props) => {
  return (
    <div>
      <h1>Thank you {(props.name) ? props.name : ''} for signing up!</h1>
      <p>If you have any questions, please contact support</p>
    </div>
  )
}
 
module.exports = Email
  

블로그 이미지

리딩리드

,
donaricano-btn

리엑트 폼 요소 정의


1. 리엑트의 폼 속성

- 일반적으로 리엑트는 속성을 변경할 수 없다. 그러나 폼 요소의 속성은 변경이 가능하다.

- value, checked, selected 라는 대화형 속성을 두어서 폼 요소를 특별하게 다루고 있다

- value : <input>, <textarea>, <select>

- checked: <input> 의 type="checked" 또는 type="radio"

- selected: <select>의 <option>


2. <input> 요소

1) type="text"

- value를 변경가능 속성으로 한다

- 일반적인 텍스트 영역이다.

- onChange 이벤트 핸들러를 사용한다.

1
<input type="text" name="email" value={this.state.email} onChange={this.handleEmailChange}/>

2) type="checkbox", type="radio" 

- checked 혹은 selected를 변경 가능 속성으로 한다.

- value 속성은 하드코딩을 한다

A. radio 사용하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
import React from 'react';
import ReactDOM from 'react-dom';
  
class Content extends React.Component{
    constructor(props){
        super(props)
        this.handleRadio = this.handleRadio.bind(this)
        this.state = {
            radioGroup :{
                angular: false,
                react:true,
                polymer:false
            }
        }
    }
    handleRadio(event){
        let obj = {}
        obj[event.target.value] = event.target.checked
         
        this.setState({radioGroup:obj})
    }
    render(){
        return <form>
          <input type="radio"
              name="radioGroup"
              value='angular'
              checked={this.state.radioGroup['angular']}
              onChange={this.handleRadio}/> angular
          <input type="radio"
              name="radioGroup"
              value='react'
              checked={this.state.radioGroup['react']}
              onChange={this.handleRadio}/> react
        <input type="radio"
            name="radioGroup"
            value='polymer'
            checked={this.state.radioGroup['polymer']}
            onChange={this.handleRadio}/> polymer
        </form>
    }
}
  
ReactDOM.render(
  <Content/>,
  document.getElementById('app')
);
 

- 객체를 교체하는 방법을 이용하여 radio의 checked 를 할당한다

B. checkbox 사용하기

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
import React from 'react';
import ReactDOM from 'react-dom';
  
class Content extends React.Component{
    constructor(props){
        super(props)
        this.handleCheckBox = this.handleCheckBox.bind(this)
        this.state = {
         
            checkboxGroup:{
                node:false,
                react:true,
                express:false,
                mongodb:false
            }
        }
    }
    handleCheckBox(event){
        let obj = Object.assign(this.state.checkboxGroup)
        obj[event.target.value] = event.target.checked
        this.setState({checkboxGroup:obj})
    }
    render(){
        return <form>
          <input type="checkbox"
              name="checkboxGroup"
              value='node'
              checked={this.state.checkboxGroup['node']}
              onChange={this.handleCheckBox}/> node
          <input type="checkbox"
              name="checkboxGroup"
              value='react'
              checked={this.state.checkboxGroup['react']}
              onChange={this.handleCheckBox}/> react
        <input type="checkbox"
            name="checkboxGroup"
            value='express'
            checked={this.state.checkboxGroup['express']}
            onChange={this.handleCheckBox}/> express
       
        <input type="checkbox"
            name="checkboxGroup"
            value='mongodb'
            checked={this.state.checkboxGroup['mongodb']}
            onChange={this.handleCheckBox}/> mongodb
        </form>
    }
}
  
ReactDOM.render(
  <Content/>,
  document.getElementById('app')
);
 

- assign()를 이용하여 객체의 병합을 통해서 checked를 할당한다

블로그 이미지

리딩리드

,
donaricano-btn

리액트 폼 이벤트 설정


0. 제어컴포넌트와 비제어 컴포넌트

- 제어컴포넌트 : 컴포넌트 내부 상태와 뷰를 항상 동기화 시키는 방식, React가 값을 통제하거나 설정한다. (value 속성존재)

- 비 제어컴포넌트: 간단한 폼을 작성한다면 비 제어 컴포넌트를 추천한다. 제어와 다르게 값을 react가 통제하지 않는다


1. 제어 컴포넌트 

1) 기본사용

- react 에서는 기본적으로 단방향 바인딩을 이용하여 간결함을 유지한다

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
class Form extends React.Component{
    constructor(props){
        super(props)
        this.state = {title:'aaa'}
    }
    handleChange(event){
        this.setState({title: event.target.value})
    }
    render(){
        return <div>
                <input type='text' name="title" value={this.state.title} onChange={this.handleChange.bind(this)}/>{this.state.title}
        </div>
    }
}
ReactDOM.render(
    <Form/>,
    document.getElementById('app')
)

- onChange() 를 이용하여 데이터로 상태를 관리한다.

2) 예제

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
import React from 'react';
import ReactDOM from 'react-dom';
  
class Content extends React.Component{
    constructor(props){
        super(props)
        this.handleChange = this.handleChange.bind(this)
        this.state = {
            accountNumber :''
        }
    }
    handleChange(event){
        console.log('typed:',event.target.value)
        this.setState({accountNumber:event.target.value.replace(/[^0-9]/ig, '')})
    }
    render(){
        return <div>
            Account:
            <input type="text" onChange={this.handleChange}
            placeholder="123445" value={this.state.accountNumber}/>
            <br/>
            <span>{this.state.accountNumber.length > 0 ? 'you entered:'+this.state.accountNumber: ''}</span>
            </div>
    }
 
}
  
ReactDOM.render(
  <Content/>,
  document.getElementById('app')
);
 

블로그 이미지

리딩리드

,
donaricano-btn

리액트 이벤트와 컴포넌트 데이터 교환


1. 클릭 이벤트 와 상태 저장 컴포넌트

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
class Count extends React.Component{
    constructor(props){
        super(props)
        this.state = {
            counter : 0
        }
    }
    handleClick(event){
        this.setState({counter:++this.state.counter})
    }
    render(){
        return(
            <div>
                <button onClick={this.handleClick.bind(this)} className="btn btn-primary">
                    Don't click me {this.state.counter}
                </button>
            </div>
        )
    }
 
 
}
 
 
ReactDOM.render(
    <Count/>,
    document.getElementById('app')
)

- 이벤트와 상태를 같이 사용함으로 동적인 UI 구성이 가능해진다


2. 클릭 이벤트 와 상태 저장/비저장 컴포넌트

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
class Content extends React.Component{
    constructor(props){
        super(props)
        this.handleClick = this.handleClick.bind(this)
        this.state = {
            counter : 0
        }
    }
    handleClick(event){
        this.setState({counter:++this.state.counter})
    }
    render(){
        return(
            <div>
                <DumbCount counter={this.state.counter} handler={this.handleClick}/>
            </div>
        )
    }
 
 
}
 
const DumbCount = (props) => {
    return <button onClick={props.handler} className="btn btn-primary">
        Increase Volume {props.counter}
    </button>
}
 
 
ReactDOM.render(
    <Content/>,
    document.getElementById('app')
)

- DumbCount라는 비저장 컴포넌트를 생성했다.

- 부모 컴포넌트(Content) 에서 자식 컴포넌트(dumbCount)로 이벤트 핸들러를 전송하여 비저장 상태컴포넌트에서 이벤트가 작동하도록 했다


3. 컴포넌트간의 데이터 교환

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
class Content extends React.Component{
    constructor(props){
        super(props)
        this.handleClick = this.handleClick.bind(this)
        this.state = {
            counter : 0
        }
    }
    handleClick(event){
        this.setState({counter:++this.state.counter})
    }
    render(){
        return(
            <div>
               <DumbCount handler={this.handleClick}/>
                <br/>
                <Counter value={this.state.counter}/>
            </div>
        )
    }
 
}
 
const Counter = props => <span>Clicked {props.value}</span>
 
const DumbCount = props => <button onClick={props.handler} className="btn btn-primary">Don't do that</button>
 
 
ReactDOM.render(
    <Content/>,
    document.getElementById('app')
)

DumbCount, Counter라는 두개의 비저장 컴포넌트를 만들고 상위로 부모 컴포넌트인  Content 를 두어서 데이터 교환을 한다

- 컴포넌트 간의 강한 결합을 방지하고자 상위 컴포넌트를 매개의 역할 로 사용한다.

- 주로 이벤트 핸들러는 상위컴포넌트에 작성하지만 이벤트가 하나의 자식에게만 영향을 끼친다면 해당 컴포넌트에 작성하도록 한다.  


블로그 이미지

리딩리드

,