본문 바로가기
React

ValidationSample.js ( ref 함수 사용 + 유효성 검사 예제 )

by 정정훈의 아날로그 2021. 4. 20.

ValidationSample.css

1
2
3
4
5
6
7
8
.success {
  background-color: lightgreen;
}
 
.failure {
  background-color: lightcoral;
}
 
cs

 

ValidationSample.js

 

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
import React, { Component } from "react";
import "./ValidationSample.css";
 
class ValidationSample extends Component {
  state = {
    password: "",
    clicked: false,
    validated: false,
  };
 
  handleChange = (e) => {
    this.setState({
      password: e.target.value,
    });
  };
 
  handleButtonClick = () => {
    this.setState({
      clicked: true,
      validated: this.state.password === "0000",
    });
    this.test.focus();
  };
 
  render() {
    return (
      <div>
        <input
          ref={(ref) => {
            this.test = ref;
          }}
          type="password"
          value={this.state.password}
          onChange={this.handleChange}
          className={
            this.state.clicked
              ? this.state.validated
                ? "success"
                : "failure"
              : ""
          }
        />
        <button onClick={this.handleButtonClick}>검증하기</button>
      </div>
    );
  }
}
 
export default ValidationSample;
 
cs

 

handleChange 함수는 this.state.password 를 변경해준다.

 

handleButtonClick 함수는 this.state.clicked 를 true 로 변경해주고,

입력한 password가 0000일 경우this.state.validated 를 true 로 변경해준다.

22번째 줄 'this.test.focus();' 는 ref를 달아놓은 input에 focus를 주는 구문이다.

 

ref 란 html에서 해당 DOM 을 관리하기 위해 id 값을 주는것처럼

React 내부에서 DOM 을 관리하기 위해 사용하는것이다.

 

1
<input ref={(ref)=>{this.input = ref}}/>
cs

이런 형태로 설정할수 있고, 이렇게 설정한 ref는 this.input 으로 찾을수있다.

 

HTML 의 id = React 의 ref

 

 

 

'React' 카테고리의 다른 글

map() + @  (0) 2021.04.21
Component 에 ref 설정하기  (0) 2021.04.20
EventPractice2 ( input 여러 개를 핸들링 )  (0) 2021.04.20
EventPractice.js (onChange 이벤트)  (0) 2021.04.19
Component / Props / State  (0) 2021.04.19