728x90
반응형
이 글은 [리액트를 다루는 기술](저자 김민준, 출판사 길벗) 교재를 보고 공부하며 정리한 글임.
버튼을 누르면 위아래로 이동하게끔 응용
ScrollBox.js
import React, {Component} from 'react';
class ScrollBox extends Component {
scrollChange = (param)=> {
const {scrollHeight, clientHeight} = this.box;
if(param === 'u'){
this.box.scrollTop = scrollHeight - clientHeight;
}
else{
this.box.scrollTop =0;
}
}
/*
//비구조화 할당 문법
scrollToBottom=()=>{
const{scrollHeight, clientHeight}=this.box;
//this.box.scrollTop = scrollHeight - clientHeight;
if(param==='u'){
this.box.scrollTop = scrollHeight - clientHeight;
}
else{
this.box.scroll=0;
}
}
*/
render(){
const style={
border:'1px solid black',
height:'300px',
width:'300px',
overflow:'auto',
position:'relative'
};
const innerStyle = {
widht:'100%',
height:'650px',
background:'linear-gradient(white, black)'
}
return(
<div
style={style}
ref={(ref) => {this.box = ref}}>
<div style={innerStyle}/>
</div>
);
}
}
export default ScrollBox;
App.js
import React, {Component} from 'react';
import ScrollBox from './ScrollBox';
class App extends Component{
state ={
upDown :'u',
value: 'To Bottom',
}
upOrDown = () => {
if(this.state.upDown ==='u'){
this.setState({
upDown:'d',
value:'To top',
});
}
else{
this.setState({
upDown:'u',
value:'To Bottom',
})
}
}
render(){
return(
<div>
<ScrollBox ref={(ref)=>this.scrollBox=ref}/>
<button onClick={()=>{
this.scrollBox.scrollChange(this.state.upDown);
this.upOrDown();
}}>
이동
</button>
</div>
);
}
}
export default App;
728x90
반응형