reactjs - 有条件地在循环内添加引用
问题描述
我根据索引有条件地将差异引用(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>
));
解决方案
您可以使用三元运算符根据索引分配值。还要确保===
在比较值时使用:
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>
);
});
推荐阅读
- javascript - 如何使用异步存储实现“稍后提醒我”按钮?
- jquery - jquery not selector 无法正常工作
- python - 重塑输出尺寸以适应 Keras 模型
- python-3.x - Pyspark 'from_json',数据框为所有 json 值返回 null
- docker - Entrypoint not found when deployed to Fargate. Locally works
- mysql - 如何在一个 mysql 字段中创建两个条件?
- android - 无法使用“adb reverse”连接到开发服务器:spawnSync adb ENOENT
- angular - Angular:如何拦截服务器发送的事件请求?
- php - laravel编辑表单中的选定记录不起作用
- javascript - 我如何使这段代码更干净?