首页 > 解决方案 > 有条件地在循环内添加引用

问题描述

我根据索引有条件地将差异引用(ref =)分配给循环内的元素。我知道下面是错误的(虽然有效),我应该如何重构?

const SortableItem = SortableElement(({ value, index }) => (
  <div className="grid-item">
    {index == 0 && (
      <img className="image-item" src={value.imgUrl} ref={this.bigImage} />
    )}

    {index == 1 && (
      <img className="image-item" src={value.imgUrl} ref={this.secondImage} />
    )}

    {index > 1 && <img className="image-item" src={value.imgUrl} />}
  </div>
));

标签: reactjs

解决方案


您可以使用三元运算符根据索引分配值。还要确保===在比较值时使用:

const SortableItem = SortableElement(({ value, index }) => {
  const ref = index === 0 ? this.bigImage : index === 1 ? this.secondImage : null;
  return (
    <div className="grid-item">
      <img className="image-item" src={value.imgUrl} ref={ref} />
    </div>
  );
});

推荐阅读