DOM을 꼭 직접적으로 건드려야 할 때
1. 특정 input에 포커스 주기
2. 스크롤 박스 조작하기
3. Canvas 요소에 그림 그리기 등
<input ref={(ref)=>{this.input=ref}} />
import React, { Component } from "react";
export default class RefSample extends Component {
input = React.createRef();
handleFocus = () => {
this.input.current.focus();
};
render() {
return (
<div>
<input ref={this.input} />
</div>
);
}
}
import React, { Component } from "react";
import "./styles.css";
export default class ValidationSample extends Component {
state = {
password: "",
clicked: false,
validates: false
};
handleChange = (e) => {
this.setState({ password: e.target.value });
};
handleButtonClick = () => {
this.setState({
clicked: true,
validated: this.state.password === "0000"
});
};
render() {
return (
<div>
<h1>ref 연습</h1>
<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>
);
}
}
import React, { Component } from "react";
import ScrollBox from "./ScrollBox";
export default class App extends Component {
render() {
return (
<div className="App">
<ScrollBox ref={(ref) => (this.scrollBox = ref)} />
<button onClick={() => this.scrollBox.scrollToBottom()}>
맨 밑으로
</button>
</div>
);
}
}
import React, { Component } from "react";
export default class ScrollBox extends Component {
scrollToBottom = () => {
const { scrollHeight, clientHeight } = this.box;
this.box.scrollTop = scrollHeight - clientHeight;
};
render() {
const style = {
border: "1px solid black",
height: "300px",
width: "300px",
overflow: "auto",
position: "relative"
};
const innerStyle = {
width: "100%",
height: "650px",
background: "linear-gradient(white,black)"
};
return (
<div
style={style}
ref={(ref) => {
this.box = ref;
}}
>
<div style={innerStyle}></div>
</div>
);
}
}