代码之家  ›  专栏  ›  技术社区  ›  Webwoman

ReactJS—如何检测元素是其父元素在ReactJS中的第n个子级还是最后一个子级?

  •  0
  • Webwoman  · 技术社区  · 6 年前

    我试图在ReactJS中进行一些动态移动,因此我需要检查子节点相对于其父节点的位置,请问如何在ReactJS中检测到它?

    我见过 this post 但它是针对组件之间的检测,特定组件内部没有,例如:

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

    任何暗示都很好,

    1 回复  |  直到 6 年前
        1
  •  1
  •   Andy    6 年前

    好 啊。以下是我将如何处理这个问题(根据我的评论)。简而言之,使用一组对象来描述旋转木马面板,然后 map 在它上面,每次迭代都创建一个新的面板。每个面板都附加了数据属性,这些属性描述了当前面板索引和数组长度。然后可以在click处理程序中作为计算的一部分使用它们。

    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>