gpt4 book ai didi

javascript - 每次在 React 中创建元素时,我找不到在元素上获取 css 过渡的方法

转载 作者:行者123 更新时间:2023-12-02 20:48:55 25 4
gpt4 key购买 nike

每次在 React 中创建元素时,我找不到一种方法来获取该元素的 css 转换。我创建了一个简单的应用程序,其中包含很少的组件和 React 上下文。我希望在创建的每个“项目”组件上进行不透明度的过渡。但我不知道如何进行。每次单击“项目”组件时,我都会设法更改类,但每次创建组件时我都希望进行转换。我应该在某个地方使用 setTimeOut 吗?我应该使用 useEffect 吗?

这是我的代码:

// This is my Context

import React, { createContext, useState, useEffect } from "react";

export const Context = createContext();

export const ContextProvider = (props) => {
const [currentProjects, setCurrentProjects] = useState(() => {
const localData = localStorage.getItem("currentProjects");
return localData ? JSON.parse(localData) : [];
});

useEffect(() => {
localStorage.setItem("currentProjects", JSON.stringify(currentProjects));
console.log("currentProjects got updated");
}, [currentProjects]);

return (
<Context.Provider value={[currentProjects, setCurrentProjects]}>
{props.children}
</Context.Provider>
);
};

//这是我的 ProjectList 组件

import React, { useContext, useEffect } from "react";
import Project from "./Project.js";
import { Context } from "./Context.js";
import "./ProjectList.css";

const ProjectList = () => {
const [currentProjects, setCurrentProjects] = useContext(Context);


return (
<div className="ProjectListContainer">
{currentProjects.map((item) => {
return (
<Project
artist={item.artist}
project={item.project}
label={item.label}
/>
);
})}
</div>
);
};

export default ProjectList;

//这是我的项目组件

import React, { useContext, useEffect, useState, Component } from "react";
import "./Project.css";

const Project = ({ artist, project, label, light }) => {
// const [status, setStatus] = useState({ clicked: false });
// const divGotCliked = (e) => {
// setStatus({ clicked: !status.clicked });
// };

return (
<div className="ProjectContainer">
<div className="container1">
<div>
<h2>{artist} </h2>
<h2>{project} </h2>
<h2>{label} </h2>
</div>
</div>
</div>
);
};

export default Project;

最佳答案

您可以使用不重复的关键帧动画。当元素出现时,会触发此动画。

document.querySelector('.add-box').onclick = () => {
const box = document.createElement('div')
box.className = 'box'
document.body.append(box)
}
@keyframes appear {
from {
opacity: 0;
transform-origin: left;
transform: scale(0);
}
}

.box {
animation: appear .5s ease-in-out;
transition: all .5s ease-in-out;
}

body {
background: slategray;
display: flex;
flex-wrap: wrap;
}

button,
.box {
background: pink;
width: 3rem;
height: 3rem;
margin-left: 0.4rem;
margin-bottom: 0.4rem;
}

button {
background: aliceblue;
}
<button class="add-box">+</button>

关于javascript - 每次在 React 中创建元素时,我找不到在元素上获取 css 过渡的方法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61663857/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com