【发布时间】:2020-04-22 19:13:55
【问题描述】:
当我点击触发转换的不同面板时,我试图添加和删除活动类,所以如果我点击不同的面板它会起作用,因为它会触发转换,然后在点击其他面板时结束它,但是如果我想点击一个已经打开和关闭的面板,它不会在第一次点击时再次触发它,这不是好的用户体验。 我正在用 React 编写它,而且我是初学者,所以也许我做的不对。 你可以看到下面的代码,我希望我提供了所有正确的信息。
componentDidMount() {
ReactDom.findDOMNode(this).addEventListener("transitionend", (e) => {
if (
e.propertyName.includes("flex") &&
e.target.classList.contains("open")
) {
e.target.classList.add("open-active");
}
});
ReactDom.findDOMNode(this).addEventListener("click", (e) => {
const elems = document.querySelector(".open-active");
if (elems !== null) {
elems.classList.remove("open-active", "open", "opac");
}
e.target.className = "open-active";
console.log(e);
});
}
render() {
const { index, top, bottom, image, open, onClick } = this.props;
const style = {
backgroundImage: `url(${image})`,
};
const openValue = open ? "open opac" : "";
return (
<div
className={`panel ${openValue}`}
style={style}
onClick={() => {
onClick(index);
}}
>
</div>
还有 CSS
.panel > * {
margin: 0;
width: 100%;
transition: transform 0.5s;
flex: 1 0 auto;
display: flex;
justify-content: center;
align-items: center;
}
.panel > *:first-child {
transform: translateY(-100%);
}
.panel.open-active > *:first-child {
transform: translateY(0);
}
.panel > *:last-child {
transform: translateY(100%);
}
.panel.open-active > *:last-child {
transform: translateY(0);
}
.panel p:nth-child(2) {
font-size: 4em;
}
.panel.open {
font-size: 16px;
flex: 5;
}
【问题讨论】:
-
这能回答你的问题吗? Toggle Class in React
-
通常不会在 React 中使用
addEventListener和classList。相反,您将类列表绑定到状态中的某物,状态的更改会导致添加或删除类。 -
我知道这可能不是最佳做法,我会尝试对其进行更改以使其变得更好。
标签: javascript reactjs css-transitions