我有一个侧面板,里面有一些列表项。我正在使用 switch case 返回列表项。我没有为列表项重复代码,而是创建了一个列表项组件并将图标和时间戳传递给它,还在列表项组件中呈现子项。
下面是代码,
switch(item.type) {
case 'uploaded':
return (
<ListItem icon={<Svg/>} text={name +
'created item' + item.name} timestamp={timestamp}>
<div className="image">
<Image
width={70}
height={70}
item_id={item.id}
/>
</div>
</ListItem>
);
case 'deleted':
return (
<ListItem icon={<Svg/>} text={name +
'deleted item' + item.name} timestamp={timestamp}>
</ListItem>
);
function ListItem(props) {
return (
<li className="item">
<div className="details">
{props.icon}
<span>{props.text}</span>
</div>
{props.children}
<Timestamp>{props.timestamp}</Timestamp>
</li>
);
}
上面的代码有效..
但我想要一个更简洁的方法来做到这一点。而不是将文本作为 prop 传递给 ListItem 有没有办法我可以将它包含在 props.children 中并在 Listitem 中使用它..它会在带有详细信息类名的 div 之后添加...我希望它与详细信息 div 和带有类名详细信息的 div 之后的图像..
我该怎么做。谢谢。
最佳答案
您可以将所有内容移动到一个传递您的类型的新组件中:
function InnerItem(props) {
switch(props.type) {
case 'uploaded':
return (
<ListItem icon={<Svg/>} text={name +
'created item' + item.name} timestamp={timestamp}>
<div className="image">
<Image
width={70}
height={70}
item_id={item.id}
/>
</div>
</ListItem>
);
case 'deleted':
return (
<ListItem icon={<Svg/>} text={name +
'deleted item' + item.name} timestamp={timestamp}>
</ListItem>
);
}
function ListItem(props) {
return (
<li className="item">
<div className="details">
{props.icon}
<span>{props.text}</span>
</div>
<InnerItem {...item}/>
<Timestamp>{props.timestamp}</Timestamp>
</li>
);
}
关于css - 如何使用 React 重构 switch case 的代码?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55627160/