gpt4 book ai didi

javascript - 单击调整div的大小

转载 作者:行者123 更新时间:2023-12-01 16:16:56 24 4
gpt4 key购买 nike

我一直在尝试向 div 添加一个 onClick 事件,该事件会在单击该 div 时将 div 的大小调整为全屏,但是当我单击一个 div 时,所有的 div 都会展开。如何将 onClick 事件限制为仅单个 div 并使该单个 div 调整为全屏?我还添加了过渡,这样当它调整到全屏时,它看起来像一个动画,但是当只点击一个 div 时所有的 div 都受到它的影响

import React from "react";
import "./styles.scss";

const colors = [
"palevioletred",
"red",
"green",
"blue",
"yellow",
"orange",
"lightblue"
];

const randomColor = items => {
return items[randomHeight(0, items.length)];
};

const randomHeight = (min, max) => {
return Math.floor(min + Math.random() * (max - min + 1));
};

export default class App extends React.Component {
constructor(props) {
super(props);
this.addActiveClass = this.addActiveClass.bind(this);
this.state = {
active: false
};
}
addActiveClass() {
const currentState = this.state.active;
this.setState({ active: !currentState });
}
render() {
return (
<div class="container">
{Array.from({ length: 30 }).map((item, index) => (
<div
key={index}
style={{
background: randomColor(colors),
height: randomHeight(100, 200)
}}
className={this.state.active ? "full" : null}
onClick={this.addActiveClass}
/>
))}
</div>
);
}
}
* {
box-sizing: border-box;
}

body {
margin: 40px;
background-color: #fff;
color: #444;
font: 2em Sansita, sans-serif;
}

.container {
display: flex;
flex-direction: column;
flex-wrap: wrap;
max-height: 100vh;
}

.container > * {
border: 2px solid orange;
border-radius: 5px;
margin: 10px;
padding: 10px 20px;
background-color: red;
color: #fff;
}

.full{
width: 100%;
height: 100%;
transition: 2s;
}

codesandbox

最佳答案

目前您与所有 div 共享一个状态。为了解决这个问题,创建activeIndex 状态,用-1 初始化它,然后像这样使用它:

  // ...

class App extends React.Component {
constructor(props) {
super(props);
this.addActiveClass = this.addActiveClass.bind(this);
this.state = {
activeIndex: -1
};
}
addActiveClass(activeIndex) {
this.setState(prev => ({
activeIndex: prev.activeIndex === activeIndex ? -1 : activeIndex
}));
}

render() {
return (
<div className="container">
{Array.from({ length: 30 }).map((item, index) => {
return (
<div
key={index}
style={{
background: randomColor(colors),
height: randomHeight(100, 200)
}}
className={this.state.activeIndex === index ? "full" : ""}
onClick={() => this.addActiveClass(index)}
/>
);
})}
</div>
);
}
}

关于javascript - 单击调整div的大小,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/63048238/

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