리액트 폼 이벤트 설정
0. 제어컴포넌트와 비제어 컴포넌트
- 제어컴포넌트 : 컴포넌트 내부 상태와 뷰를 항상 동기화 시키는 방식, React가 값을 통제하거나 설정한다. (value 속성존재)
- 비 제어컴포넌트: 간단한 폼을 작성한다면 비 제어 컴포넌트를 추천한다. 제어와 다르게 값을 react가 통제하지 않는다
1. 제어 컴포넌트
1) 기본사용
- react 에서는 기본적으로 단방향 바인딩을 이용하여 간결함을 유지한다
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) 예제
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'
)
);
'Front-End > ReactJs' 카테고리의 다른 글
[ReactJs] node.js를 이용한 react 컴포넌트 렌더링 (0) | 2018.08.12 |
---|---|
[ReactJs] 리엑트 폼 요소 정의 (0) | 2018.08.07 |
[ReactJs] 리액트 이벤트와 컴포넌트 데이터 교환 (0) | 2018.08.05 |
[ReactJs] 리액트 컴포넌트 라이프사이클 (0) | 2018.08.05 |
[ReactJs] 리액트 상태저장 컴포넌트와 상태비저장 컴포넌트 (0) | 2018.08.05 |