728x90
- 리액트에서는 DOM에 이름을 달기 위해 ref를 사용한다.
- ID를 사용하지 않는 이유?
- HTML에서는 ID가 유일하여야 하는데 컴포넌트는 여러 번 사용될 수 있기 때문에 적절하지 않다.
- ref 같은 경우에는 전역적으로 작동되지 않고 컴포넌트 내부에서만 작동되기 때문에 이런 문제가 발생하지 않는다.
- ID를 사용하지 않는 이유?
- DOM을 직접적으로 건드려야 될 때 ref를 사용하게 된다.
-
<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width"> <title>Example</title> <style> .success{ background-color: green; } .failure{ background-color: red; } </style> <script> function validation(){ var input = document.getElementById('password'); input.className = ''; if(input.value === '0000'){ input.className = 'success'; }else{ input.className ='failure'; } } </script> </head> <body> <input type="password" id="password" ></input> <button onclick="validation()">Validation</button> </body> </html> - 리액트로 변환
- ValidationSample.css
-
.success { background-color: green; } .failure { background-color: red; }
-
- ValidationSample.js
-
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", }); }; render() { return ( <div> <input 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;
-
- App.js
-
import React, { Component } from "react"; import ValidationSample from "./ValidationSample"; class App extends Component { render() { return <ValidationSample />; } } export default App;
-
- input 태그에 onchange 이벤트가 발생하면 handleChange를 호출하여 state의 password값을 업데이트해주었다.
- button에 onClick 이벤트가 발생하면 handleButtonClick을 호출하여 clicked를 참으로, validated 값을 검증 결과로 설정하였다.
- 버튼을 누른 후에는 검증 결과에 따라 className값을 success, failure값으로 설정한다(className 값에 따라 색상이 다르게 보이게 한다.)
- ValidationSample.css
- 위와 같은 경우에는 State로 충분히 해결이 가능하지만 반드시 DOM에 접근해서 해결해야 될 경우가 존재한다.
- 특정 input에 포커스 주기
- 스크롤 박스 조작하기
- Canvas 요소에 그림 그리기 등
728x90
'리액트 > ref:DOM에 이름달기' 카테고리의 다른 글
| ch03.컴포넌트에 ref 달기 (0) | 2021.11.09 |
|---|---|
| ch02.ref 사용 (0) | 2021.11.09 |