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

时间:2019-01-18 15:54:46

标签: javascript css reactjs

我正在尝试在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 个答案:

答案 0 :(得分:1)

好。这是我的处理方式(与我的评论一致)。简而言之,使用一系列对象来描述您的轮播面板,然后在其上map,每次迭代都创建一个新面板。每个面板都有附加的数据属性,它们描述当前面板索引和数组长度。然后可以在点击处理程序中将它们用作计算的一部分。

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>