如何使用 for 循环向 React 组件添加样式 [英] How to add styles to React Component with a for loop

查看:23
本文介绍了如何使用 for 循环向 React 组件添加样式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想设置每个 React 组件相对于其在数组中的索引的顶部样式,但是,我不确定如何正确访问和设置该属性.我会使用 state 设置它们,但是,包含我要操作的元素的节点是我正在编辑的节点的同级节点的子节点.有什么方法可以有效地做到这一点?

I'm wanting to set the top style of each React component relative to its index in the array, however, I am unsure how to access and set the property correctly. I would set them using state, however, the node containing the element which I want to manipulate is a child node of a sibling node from the node which I am editing from. Any way to do this effectively?

handleClick3D() {
    document.getElementById('portfolio').classList.replace('portfolio-2d', 'portfolio-3d');
    var elems = document.querySelectorAll('.portfolio-item');
    for (var i = 0; i < elems.length; i++) {
        var zIndex = 0 + i;
        elems[i].zIndex = zIndex;
        elems[i].firstChild.src = items[i].imgSec;
        elems[i].style.top = 0 - (i * 300);
    }
}

'portfolio-item' 类应用于每个元素,我以这种方式选择每个元素,因为我认为我无法访问实际的 React 组件,因为它位于同级节点树中.

The 'portfolio-item' class is applied to each element and I am selecting each element that way as I don't think I can access the actual React component seeing as it lives in a sibling node tree.

提前致谢!

推荐答案

使用 .map 函数并返回不同样式或道具的 jsx 组件

use .map function and return jsx component with different style or props

链接

这篇关于如何使用 for 循环向 React 组件添加样式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆