简体   繁体   中英

How can I loop through all the elements in my reactjs component?

I have a reactjs component that looks something like this:

<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?

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

<div className="wrapper">
   {
      [...Array(25)].map((un, index) => (
          <div key={index} className={yourClassName} ref={yourRef} />
        )
      )
   }
</div>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM