HexColors 레퍼런스
알게된 점
css animation을 처음 사용해봄 → css만으로 글씨색을 자동으로 바꿀 수 있음
.hex-color_container {
...
animation: changeColor 5s infinite alternate;
한번 실행 시 5초 / 무한 반복 / 지정된 방향 -> 반대 방향 순
@keyframes changeColor {
0% {
color: indigo;
}
20% {
color: blue;
}
40% {
color: green;
}
60% {
color: yellow;
}
80% {
color: orange;
}
100% {
color: red;
}
}
}
문제는 state(배경색 코드)가 바뀔 때마다 모든 html이 다시 렌더링되도록 구현하니까 글씨 컬러 애니메이션도 처음부터 시작하게 됨
- state+재렌더링 방법 사용 x
- html을 처음에만 생성하고 배경색이 바뀌어야할 땐(이벤트 발생) 직접 해당돔에 접근해서 textcontent와 background-color 속성 값만 변경해주니까 해결되었다
리액트는 상태가 변할 때마다 돔이 다시 렌더링되는데 어떻게 구현할까?
- 구현해본 결과 styled component와 scss두 경우 다 상태가 변해도 애니메이션이 다시 시작되지 않았다
- 전부 새로 재렌더링 되는 것은 가상 돔이고, 진짜 돔에는 변한 돔에만 접근해서 값을 바꿔주는 것이지 새로 생성하는 것이 아니기 때문이었다
코드
class HexColors extends Component<undefined> {
$container: Element;
$title: Element;
constructor($target: Element) {
super($target);
this.render();
this.$container = document.querySelector('.hex-color_container');
this.$title = document.querySelector('.color-code');
}
template(): string {
return `
<div class='hex-color_container'>
<div class='content'>
<h1 class='title'>CLICK THE BUTTON BELLOW TO DISPLAY THE HEX CODE </br> OF THE A RANDOM COLOR</h1>
<p class='color-code'>The hex code of the color is '#ffffff'</p>
<button class='change_button'>click me</button>
</div>
</div>
`;
}
_getRandomColor() {
return '#' + Math.round(Math.random() * 0xffffff).toString(16);
}
handleChangeBackColor() {
const backColorCode = `linear-gradient( to left, ${this._getRandomColor()}, ${this._getRandomColor()} )`;
if (this.$container instanceof HTMLElement) {
this.$container.style.background = backColorCode;
}
this.$title.innerHTML = `The hex code of the color is ${backColorCode}`;
}
mount() {
const $button = document.querySelector('.change_button');
$button?.addEventListener('click', () => {
this.handleChangeBackColor();
});
}
render() {
this.$target.innerHTML = '';
this.$target.innerHTML = this.template();
this.mount();
}
}
export default HexColors;