ref의 특징: single DOM element에 접근할 수 있게 해준다.
- constructor function안에서 ref를 만든다.
- 그 ref를 instance variable로 선언한다.
- 그 ref를 JSX에 props로 전달해준다.
class ImageCard extends React.Component {
constructor(props) {
super(props);
this.imageRef = React.createRef();
}
render() {
const { description, urls } = this.props.image;
return (
<div>
<img ref={this.imageRef} alt={description} src={urls.regular} />
</div>
);
}
}
이렇게 접근한 DOM element에 CSS grid 스타일링을 넣어보자
/* ImageList.css */
.image-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
grid-gap: 0 10px;
grid-auto-rows: 10px;
}
.image-list img {
width: 250px;
grid-row-end: span 2;
}
import React from 'react';
class ImageCard extends React.Component {
constructor(props) {
super(props);
this.state = { spnas: 0 };
this.imageRef = React.createRef();
}
componentDidMount() {
this.imageRef.current.addEventListener('load', this.setSpans);
}
setSpans = () => {
const height = this.imageRef.current.clientHeight;
const spans = Math.ceil(height / 10);
this.setState({ spans });
}
render() {
const { description, urls } = this.props.image;
return (
<div style={{ gridRowEnd: `span ${this.state.spans}` }}>
<img ref={this.imageRef} alt={description} src={urls.regular} />
</div>
);
}
}
export default ImageCard;