728x90
ref는 DOM을 꼭 직접적으로 건드려야할 때 사용한다.
즉, 컴포넌트 내부에서 DOM에 직접 접근해야할 때 !
ex )
class App extends Component {
render() {
return (
<div>
<ScrollBox ref={(ref)=>this.scrollBox=ref}/>
<button onClick={()=>this.scrollBox.scrollToBottom()}>
맨 밑으로
</button>
</div>)
}
}
ScollBox 컴포넌트 태그 내부에 작성한ref는 ScrollBox컴포넌트 내부에서 작성한
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>
);
}
}
ref를 의미한다. (즉, 스크롤박스의 상단과 하단)
스크롤박스 컴포넌트 내부에, scrollToBottom 함수를 만들어 주었기 때문에,
App.js에서 이러한 함수를 사용하려면 ref를 필요로 한다.
ref가 없을시 함수 호출이 되지 않음!!
728x90