ref(reference): DOM에 이름달기
1. 클래스형 컴포넌트
1) ref객체 생성
input = React.createRef();
2) DOM요소 ref속성으로 지정
<input ref = {this.input} />
3) DOM요소 접근
this.input.current
2. 함수형 컴포넌트
1) useRef import
import { useRef } from 'react';
2) ref 객체
const input = useRef();
3) DOM요소 지정
<input ref={input} />
4) DOM요소 접근
input.current
App.js
import './App.css';
// import RefInput from './Components/RefInput';
// import EventInputClass from './Components/EventinputClass';
import EventInput from './Components/EventInput';
// import RefClassSample from './Components/refClassSample';
function App() {
return (
<div className="App">
{/* <RefInput /> */}
{/* <RefClassSample/> */}
<EventInput/>
{/* <EventInputClass /> */}
</div>
);
}
export default App;
EventInput.js
import React, { useState, useRef } from 'react';
const EventInput = () => {
const input = useRef();
const [form, setForm] = useState({
username:"",
message:"",
});
const { username, message } = form;
const onChange = e => {
// const nextForm = {
// // usrname: "",
// // message:"",
// ...form, // 기존의 form 내용을 여기에 복사
// [e.target.name]: e.target.value // 원하는 값은 덮어 씌우기
// }
// setForm(nextForm);
const { name, value } = e.target;
setForm({
...form,
[name]: value
});
}
const onKeyPress = (e) => {
if(e.key === "Enter") {
onClick();
}
}
// 버튼 클릭시 실행할 함수
const onClick = () => {
console.log(`메세지는 ${message}이고 유저네임은 ${username}입니다.`);
setForm({
username: "",
message: "",
});
input.current.focus();
}
return (
<div>
<h1>이벤트 연습</h1>
<input type="text" ref={input} name="username" value={username} onChange={onChange} onKeyPress={onKeyPress}/>
<input type="text" name="message" value={message} onChange={onChange} onKeyPress={onKeyPress}/>
<button onClick={onClick}>확인</button>
</div>
);
};
export default EventInput;
EventInputClass.js
import React, {Component} from 'react';
class EventInputClass extends Component {
state = {
message: '',
username: '',
}
handleChange = (e) => {
this.setState({
// message: e.target.value
[e.target.name]: e.target.value // input이 여러개일 때 name으로 접근
})
}
handelClick = () => {
console.log(`메세지는 ${this.state.message}이고 유저네임은 ${this.state.username}입니다.`)
this.setState({
message:'',
username: '',
})
}
// 키를 누르면 실행되는 함수
handelKeyPress = (e) => {
console.log(e);
if(e.key === "Enter") {
this.handelClick();
}
}
render() { // render 안에 들어가는건 JSX 구문 여 밖에는 그냥 JS
return (
<div>
<h1>이벤트 연습</h1>
<input type="text" name="message" onChange={this.handleChange} value={this.state.message} onKeyPress={this.handelKeyPress}/>
<input type="text" name="username" onChange={this.handleChange} value={this.state.username} onKeyPress={this.handelKeyPress}/>
<button onClick={this.handelClick}>확인</button>
</div>
);
}
}
export default EventInputClass;
refClassSample.js
import React, { Component } from 'react';
import './RefSample.css'
class RefClassSample extends Component {
input = React.createRef();
state = {
password: '',
clicked: false,
validated: false
}
handleChange = () => {
this.setState({
// password: e.target.value
password: this.input.current.value
})
}
handelButtonClick = () => {
this.setState({
clicked: true,
validated: this.state.password === '0000'
})
// DOM 요소 접근은 ref.current
console.log(this.input);
this.input.current.focus()
}
render() {
return (
<div>
{/* 선택하려는 DOM요소의 ref속성으로 지정해줌 */}
<input
type="password"
ref = {this.input}
// value={this.state.password}
onChange={this.handleChange}
className={this.state.clicked ? (this.state.validated ? 'success' : 'failure') : '' }
/>
<button onClick={this.handelButtonClick}>확인</button>
</div>
);
}
}
export default RefClassSample;
refInput.js
// rcc
import React, { Component } from 'react';
class RefInput extends Component {
// ref생성
abc = React.createRef();
handleFocus = () => {
this.abc.current.focus();
console.log(this.abc.current.value);
}
render() {
return (
<div>
<input ref={this.abc} onChange = {this.handleFocus}/>
</div>
);
}
}
export default RefInput;
RefSample.css
.success {
background-color: lightgreen;
}
.failure {
background-color: lightcoral;
}
'Stack > React' 카테고리의 다른 글
[React] React Component Styling (0) | 2022.06.23 |
---|---|
[React] to-do list (0) | 2022.06.22 |
[React] 라이프 사이클 메서드(Life Cycle Method) (0) | 2022.06.21 |
[React] 컴포넌트 (0) | 2022.06.20 |
[React] 안녕 ~ React (0) | 2022.06.20 |