React - DOM - 08
Using Ref’s for DOM Access
Grid CSS
이미지 사이트에 들어가보면 아래와 같은 Grid UI를 볼 수 있다.
.image-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
grid-gap: 10px;
grid-auto-rows: 150px;
}
.image-list img {
width: 250px;
grid-row-end: span 2;
}
<div class="image-list">
<img ... />
<img ... />
</div>
Change Props
class ImageCard extends React.Component {
remder() {
return (
<div>
<img alt={this.props.images.description} src={this.props.images.urls.regular} />
</div>
)
}
}
class ImageCard extends React.Component {
render() {
const { description, urls } = this.props.images;
return (
<div>
<img alt={description} src={urls.regular} />
</div>
)
}
}
Accessing the DOM with Refs(React Refs)
- Gives access to a single DOM element
- We create refs in the constructor, assign them to instance variables, then pass to a particular JSX element as props
Accessing Image Height
import React from 'react';
class ImageCard extends React.Component {
constructor(props) {
super(props);
this.imageRef = React.createRef();
}
componentDidMount() {
console.log(this.imageRef.current);
console.log(this.imageRef.current.clientHeight);
}
render() {
const { description, urls } = this.props.image;
return (
<div>
<image ref={this.imageRef} alt={description} src={urls.regular} />
</div>
);
}
}
export default ImageCard;
Callbacks on Image Load
componentDidMount() {
this.imageRef.current.addEventListener('load', this.setSpans);
}
setSpans = () => {
console.log(this.imageRef.current.cientHeight);
}
Dynamic Spans
.image-list {
display: grid;
grid-template-columns: repeat(auto-fill, minmax(250px, 1fr));
grid-gap: 0 10px;
grid-auto-rows: 150px;
}
.image-list img {
width: 250px;
grid-row-end: span 2;
}
setSpans = () => {
const height = this.imageRef.current.clientHeight;
const spans = Math.ceil(height / 10);
this.setState({ spans: spans });
}
render() {
const { description, urls } = this.props.image;
return (
<div style={{ gridRowEnd: `span ${this.state.spans}` }}>
<image ref={this.imageRef} alt={description} src={urls.regular} />
</div>
);
}
TIP
setState할 때 바꿀 값과 기본 값이 같으면 생략 가능하다.
this.setState({ spans: spans });
this.setState({ spans });
GitHub and Others
- 강의를 들으며 따라한 내용을 pics에 올려두었습니다.
댓글
댓글 쓰기