1 回答

TA貢獻1872條經驗 獲得超4個贊
嘗試這樣:https:?//codesandbox.io/s/serene-pine-ckph1
在React中,修改組件的方式是根據它的props/state。單擊圖片容器時更新狀態,然后使用它來添加類。
圖片.js
import React, { Component } from "react";
import "../css/utilities.css";
import "../css/main.css";
class Pictures extends Component {
? constructor(props) {
? ? super(props);
? ? this.state = {
? ? ? fadeOut: false
? ? };
? ? this.fadeOut = this.fadeOut.bind(this);
? }
? fadeOut() {
? ? this.setState({ fadeOut: true }, function () {
? ? ? setTimeout(function () {
? ? ? ? document.getElementById("length").innerText--;
? ? ? }, 200);
? ? });
? }
? render() {
? ? console.log(this.props.picture);
? ? const { title, thumbnailUrl } = this.props.picture;
? ? return (
? ? ? <div
? ? ? ? className={
? ? ? ? ? "picture card container" + (this.state.fadeOut ? " fadeOut" : "")
? ? ? ? }
? ? ? ? onClick={(event) => this.fadeOut(event)}
? ? ? >
? ? ? ? <img src={thumbnailUrl} alt="" />
? ? ? ? <h1 className="title">{title}</h1>
? ? ? </div>
? ? );
? }
}
export default Pictures;
然后該類使用 CSS 平滑地應用淡出效果:
main.css
.picture {
? opacity: 1;
? transition: opacity 0.2s linear;
}
.picture.fadeOut {
? opacity: 0;
}
其他建議:
上面的代碼代替 jsonPlaceholder.js 運行,以更好地遵循框架約定并僅使用 CSS 進行樣式設置
在 HTML 中,每個id
id="picture"
屬性必須是唯一的,因此如果有超過 1 個圖片元素,則無法設置每個圖像都應該有一個alt屬性
添加回答
舉報