我有一个看起来像这样的reactjs组件:
<div className="wrapper">
<div className="box box1" ref="04"/>
<div className="box box1" ref="03"/>
<div className="box box1" ref="02"/>
</div>
实际上我刚刚列出了25个嵌套的div 3.问题是如何循环遍历这些元素以便我可以更改所有这些元素的className属性?
答案 0 :(得分:2)
您可以执行以下操作:
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'));
&#13;
<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>
&#13;
答案 1 :(得分:2)
使用JSX
<div className="wrapper">
{
[...Array(25)].map((un, index) => (
<div key={index} className={yourClassName} ref={yourRef} />
)
)
}
</div>