Javascript 重新构造重复组件以在贴图函数中渲染
虽然我尽可能枯燥地编写了我的组件,但我想知道是否有更好的方法通过将[linkedIn、twitter、researchGate]作为数组的映射函数来渲染Javascript 重新构造重复组件以在贴图函数中渲染,javascript,reactjs,Javascript,Reactjs,虽然我尽可能枯燥地编写了我的组件,但我想知道是否有更好的方法通过将[linkedIn、twitter、researchGate]作为数组的映射函数来渲染ConnectButton。我尝试了不同的方法,但这是我能得到的最好的方法。(我将代码简化为相关的代码。原始版本要长很多。) const组件=()=>{ const ConnectButton=({icon,title})=>( ); const renderConnectMenu=()=>{ 如果(!profileInfo){ 返回; } co
ConnectButton
。我尝试了不同的方法,但这是我能得到的最好的方法。(我将代码简化为相关的代码。原始版本要长很多。)
const组件=()=>{
const ConnectButton=({icon,title})=>(
);
const renderConnectMenu=()=>{
如果(!profileInfo){
返回;
}
const linkedIn=profileInfo.linkedIn;
const twitter=profileInfo.twitter;
const researchGate=profileInfo.researchGate;
返回(
{linkedIn&&}
{twitter&&}
{researchGate&&(
)}
);
};
渲染(
[...]
{renderConnectMenu()}
[...]
);
};
有3个属性定义按钮的呈现方式:profileInfo中的字段、图标和标题。因此,我们需要一组具有这些属性的对象,以便使用.map
渲染它们
我不确定profileInfo
字段的日期类型,因此我根据其用法将该属性命名为shouldRender
const renderConnectMenu = () => {
if (!profileInfo) {
return;
}
const buttons = [
{
shouldRender: profileInfo.linkedIn,
icon: faLinkedin,
title: 'LinkedIn',
},
{
shouldRender: profileInfo.twitter,
icon: faLinkedin,
title: 'Twitter',
},
{
shouldRender: profileInfo.researchGate,
icon: faLinkedin,
title: 'Research Gate',
},
];
return (
<div>
{buttons.map(
(button) =>
button.shouldRender && (
<ConnectButton
key={button.title}
icon={button.icon}
title={button.title}
/>
),
)}
</div>
);
};
const renderConnectMenu=()=>{
如果(!profileInfo){
返回;
}
常量按钮=[
{
shouldRender:profileInfo.linkedIn,
图标:faLinkedin,
标题:“LinkedIn”,
},
{
shouldRender:profileInfo.twitter,
图标:faLinkedin,
标题:“推特”,
},
{
shouldRender:profileInfo.researchGate,
图标:faLinkedin,
标题:“研究之门”,
},
];
返回(
{buttons.map(
(按钮)=>
button.shouldRender&&(
),
)}
);
};
当您有几个项目要渲染时,它可能看起来有点奇怪。因此,如果只有2-3项,我不推荐这种方法,除非有可能扩展列表。保持现状没关系
const renderConnectMenu = () => {
if (!profileInfo) {
return;
}
const buttons = [
{
shouldRender: profileInfo.linkedIn,
icon: faLinkedin,
title: 'LinkedIn',
},
{
shouldRender: profileInfo.twitter,
icon: faLinkedin,
title: 'Twitter',
},
{
shouldRender: profileInfo.researchGate,
icon: faLinkedin,
title: 'Research Gate',
},
];
return (
<div>
{buttons.map(
(button) =>
button.shouldRender && (
<ConnectButton
key={button.title}
icon={button.icon}
title={button.title}
/>
),
)}
</div>
);
};