import React from 'react';
import ValidationSample from "./ValidationSample";
import ValidationSample1 from './ValidationSample1';
import ValidationSample2 from './ValidationSample2';
function App() {
return (
<div>
<ValidationSample
ref={(ref) => {this.ValidationSample=ref}}
/>
<ValidationSample1/>
<ValidationSample2/>
</div>
);
}
export default App;
이렇게 하면 ValidationSample 내부의 메서드 및 멤버 변수에도 접근할 수 있습니다.
즉, 부모 컴포넌트에서 자식 컴포넌트 내부의 ref에도 접근할 수 있다는 의미입니다.
예) ValidationSample.handleChange, ValidationSample.input
// ScorollBox.js
import React, { Component } from "react";
class ScorollBox extends Component {
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 (
<>
<h2>스크롤박스 생성</h2>
<div
style={style}
ref={(ref) => {
this.box = ref;
}}
>
<div style={innerStyle}></div>
</div>
</>
);
}
}
export default ScorollBox;
이제 화면을 출력해봅시다.
스크롤 박스가 생성된 것을 볼 수 있습니다.
// ScorollBox.js
...
scrollToBottom = () => {
const { scrollHeight, clientHeight } = this.box;
// 이 코드는 구조분해 문법을 사용했습니다.
// const scrollHiehgt = this.box.scrollHeight;
// const clientHeight = this.box.clientHeight;
// 이 코드는 앞의 코드와 같은 의미입니다.
this.box.scrollTop = scrollHeight - clientHeight;
this.box.style.border = "4px solid red";
//작동 확인을 위한 가시성 css 변경
};
...
import React, { Component } from 'react';
import ValidationSample from "./ValidationSample";
import ValidationSample1 from './ValidationSample1';
import ValidationSample2 from './ValidationSample2';
import ScorollBox from './ScorollBox';
class App extends Component {
render() {
return (
<div>
<ValidationSample
ref={(ref) => {this.ValidationSample=ref}}
/>
<ValidationSample1/>
<ValidationSample2/>
<ScorollBox
ref={(ref) => {this.scorollBox=ref}}
/>
<button onClick={() => this.scorollBox.scrollToBottom()}>맨밑으로</button>
</div>
);
}
}
export default App;
이렇게 자식 컴포넌트 요소에 있는 함수를 작동시키는 것을 볼 수 있습니다.