컴포넌트에 스크롤바를 맨 아래쪽으로 내리는 메서드를 만들것이다.
[자바스크립트로 스크롤바를 내릴 때 DOM노드에서 사용 하는 값들]
▶ ScrollBox.js
import { Component } from 'react';
class ScrollBox extends Component {
scrollToBottom = () => {
const {scrollHeight, clientHeight} = this.box;
// 앞 코드에는 비구조화 할당 문법을 사용했습니다.
// 다음 코드와 같은 의미입니다.
// const scrollHeight = this.box.scrollHeight;
// const clientHeight = this.box.clientHeight;
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>
);
}
}
export default ScrollBox;
App 컴포넌트에서 ScrollBox에 ref를 달고 버튼을 만들어 누르면, ScrollBox 컴포넌트의 scrollToBottom 메서드를 실행하도록 코드를 작성한다.
▶ App.js
import { Component } from 'react';
import ScrollBox from './ScrollBox';
class App extends Component{
render() {
return (
<div>
<ScrollBox ref={(ref) => this.scrollBox=ref}/>
<button onClick={() => this.scrollBox.scrollToBottom()}>
맨 밑으로
</button>
</div>
);
}
}
export default App;
[주의사항]
버튼을 누르면 스크롤바가 맨 아래로 이동한다.
이 장에서는 리액트 프로젝트에서 반복적인 내용을 효율적으로 보여주고 관리하는 방법을 알아보겠다.
arr.map(callback, [thisArg])
var numbers = [1, 2, 3, 4, 5];
var processed = numbers.map(function(num){
return num * num;
});
console.log(processed);
이처럼 map 함수는 기존 배열로 새로운 배열을 만드는 역할을 한다.
이 코드를 ES6 문법으로 작성하면 다음과 같다.
const numbers = [1, 2, 3, 4, 5];
const result = numbers.map(num => num * num);
console.log(result);
var 키워드 대신 const를 사용했고, function(...){...} 대신 화살표 함수를 사용했다.
▶ IterationSample.js
const IterationsSample = () => {
const names = ['눈사람', '얼음', '눈', '바람'];
const nameList = names.map(name => <li>{name}</li>);
return <ul>{nameList}</ul>;
}
export default IterationsSample;
▶ App.js
import { Component } from 'react';
import IterationSample from './IterationSample';
class App extends Component{
render() {
return (
<IterationSample/>
)
}
}
export default App;