gpt4 book ai didi

javascript - 具有相同类的 ReactJS onClick .next() 元素?

转载 作者:行者123 更新时间:2023-11-30 11:55:30 24 4
gpt4 key购买 nike

我是 ReactJS 的新手,我想知道在 React 中定位具有相同类的下一个元素的正确方法是什么?

<div className="portfolioGallery">
<img className="portfolioImg activeImg" src="img/1.png"/>
<img className="portfolioImg" src="img/2.png"/>
<img className="portfolioImg" src="img/2.png"/>
<div className="portfolioNext" onClick={this.nextImg.bind(this)}>
Next image
</div>
</div>

当我单击 portfolioNext div 时,我能够为 img2 类提供 activeImg 并将其从 ReactJS 中的前一个元素等中删除的正确方法是什么?

谢谢!

constructor() {
super();
this.state = {
default: "portfolioImg activeImg"
};
}

nextImg() {
this.setState({
default: "portfolioImg"
});
}

最佳答案

这是您通常会在 jQuery 代码中找到的那种命令式技术,但它并不能很好地映射到 React 稍微更具声明性的性质。

与其尝试查找具有类的下一个元素,不如使用状态来维护这些元素的列表以及索引游标。

// constructor
this.state = {
images = ['img/1.png', 'img/2.png', 'img/3.png']
cursor: 0
};

然后使用这些数据位来呈现您的 View 。

// render
const { images, cursor } = this.state;
return (
<div>
{images.map((src, index) => {
const activeClass = (index === cursor) ? 'activeImg' : '';
return <img className={`portfolioImg ${activeClass}`} />;
}}
</div>
);

要更改事件图像,请使用 setState 更改 cursor 属性。

// nextImg
const { cursor, images } = this.state;
const nextCursor = cursor % images.length;

this.setState({ cursor: nextCursor });

关于javascript - 具有相同类的 ReactJS onClick .next() 元素?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38110400/

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