javascript - 编写多个 React 组件的更有效方式?
问题描述
我有一个页面,我在其中呈现 8 个组件,唯一不同的是值迭代......
<Item
classModifier="step"
image={Step1}
heading={Copy.one.heading}
/>
<Item
classModifier="step"
image={Step2}
heading={Copy.two.heading}
/>
<Item
classModifier="step"
image={Step3}
heading={Copy.three.heading}
/>
上面的工作,但是有没有更有效的方法来写这个?我知道这可能不符合 DRY 方法!
解决方案
string
创建一个包含数字格式的数组- 创建另一个数组来保存你的
Step1, Step2, ...
变量 - 根据前面描述的数组中的和其将这些项目映射
<Item>
到组件中current string
index
你会有这样的东西
const numbers = ['one', 'two', 'three'];
const steps = [Step1, Step2, Step3]; // These need to be defined before
return (
<div>
{numbers.map((s, i) => (
<Item key={i} classModifier='step' image={steps[i]} heading={Copy[s].heading}>
))}
</div>
);
编辑
- 这要求您的两个数组以相同的顺序排序。否则它将无法将步骤与其对应的编号匹配
- 为避免这种情况,您应该在数组中放置对象而不是原始字符串。查看 Gabriele 的答案以获得更强大和可维护的实现
推荐阅读
- java - @Scheduled 与 ThreadPoolTaskScheduler 行为
- python - Kivy 改变图像的纹理给出黑色图像
- android - RxJava2 + Room:clearAllTables() 调用后数据未插入 DB
- swift - Cocoa NSTask 输出提取
- php - Sphinx - Duplicated results when searching
- android - 恢复后碎片数据丢失
- php - How do I save the new Logging configuration on Laravel?
- hook - No hook files generated by PyInstaller
- java - JAVA 套接字被调用太多次
- php - Images are not accessible after moving Laravel project