1. 자식 Component 만들기 - ScrollBox.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
|
import React, { Component } from "react";
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>
);
}
}
export default ScrollBox;
|
cs |
2. 부모 Component 에서 자식 Component에 ref 달기
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
|
import React, { 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;
|
cs |
3. ref 이용해서 자식 Component 내부의 scrollToBottom 매서드 사용하기
'React' 카테고리의 다른 글
Component 의 LifeCycle (0) | 2021.04.22 |
---|---|
map() + @ (0) | 2021.04.21 |
ValidationSample.js ( ref 함수 사용 + 유효성 검사 예제 ) (0) | 2021.04.20 |
EventPractice2 ( input 여러 개를 핸들링 ) (0) | 2021.04.20 |
EventPractice.js (onChange 이벤트) (0) | 2021.04.19 |