简体   繁体   中英

ReactJS - How detect if an element is the nth _ first _ or last child of its parent in ReactJS?

I'm trying to make some dynamic moves in ReactJS hence I need to check the child-position relatively to its parent, how can I detect it in ReactJS, please?

I have seen this post but it is for the detection between components, no inside a specific component as follow for example:

<div
className={style.carousel}
>
     <div 
         id={style.carousel_item_one}
     > 
              carousel_item_1 // => first child, but how detect it?

     </div>
     <div 
         id={style.carousel_item_two}
     > 
              carousel_item_2 // => nth child, but how detect it?
     </div>
     <div 
         id={style.carousel_item_three}
     > 
              carousel_item_3 // => last child, but how detect it?
     </div>
</div>

Any hint would be great,

thanks

OK. Here's how I would approach this (in line with my comment). In short use an array of objects to describe your carousel panels, and then map over it, creating a new panel with each iteration. Each panel has data attributes attached to it that describe the current panel index and the array length. These can then be use in the click handler as part of a calculation.

 class Carousel extends React.Component { constructor() { super(); // Make sure you bind your handler this.handleClick = this.handleClick.bind(this); } handleClick(e) { // Destruct the id and length from the target dataset const { dataset: { id, length } } = e.target; // Here you would perform your calculation console.log(id, length); } render() { // Get the panel data we passed in const { panels } = this.props; // Grab the length of the panel array const { length } = panels; // `map` over the panels array to create a new panel with each // iteration. Note we also use `map`'s index parameter return panels.map((panel, index) => { // Add the index, length as element data attributes return ( <div key={index} data-id={index} data-length={length} className="carouselItem" onClick={this.handleClick} > {panel.desc} ({index} of {panels.length}) </div> ); }); } } // Panel data const panels = [{ desc: 'Panel 1' }, { desc: 'Panel 2' }, { desc: 'Panel 3' }]; ReactDOM.render( // Pass in the panel data as props <Carousel panels={panels} />, document.getElementById('container') ); 
 .carouselItem { display: inline-block; margin-right: 1em; padding: 0.3em; border: 1px solid #dfdfdf; } .carouselItem:hover { cursor: pointer; } 
 <script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.6.3/umd/react.production.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.6.3/umd/react-dom.production.min.js"></script> <div id="container"></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