[英]How can I loop through all the elements in my reactjs component?
I have a reactjs component that looks something like this: 我有一个reactjs组件,看起来像这样:
<div className="wrapper">
<div className="box box1" ref="04"/>
<div className="box box1" ref="03"/>
<div className="box box1" ref="02"/>
</div>
In reality there are 25 nested divs I just listed 3. Question is how can I loop through these elements so I can change the className property for all of them? 实际上,我刚刚列出了25个嵌套的div。3。问题是如何遍历这些元素,以便可以为所有元素更改className属性?
You could do something like the following: 您可以执行以下操作:
const Example = () => { const newArr = [...Array(25)]; return ( <div> { newArr.map((i, index) => { return ( <div key={index} className={`box${index}`}>{index}</div> ) }) } </div> ); } ReactDOM.render(<Example />, document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> <div id="root"></div>
Use JSX 使用JSX
<div className="wrapper">
{
[...Array(25)].map((un, index) => (
<div key={index} className={yourClassName} ref={yourRef} />
)
)
}
</div>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.