我试图有条件地渲染几个共享组件,但出现错误:
第182:9行:预期进行赋值或函数调用,而是看到一个表达式no-unused-expressions
以下内容在没有<Conditional />
包装器组件的情况下可以完美地工作。但是,新的客户端要求是在达到特定于组件的if-else语句之前,应在所有组件上放置更高级别的条件。我想创建一个包装器组件<Conditional />
,而不是用更多条件或重复代码来夸大现有的if-else语句。
为了适当地呈现它,我用匿名箭头功能包装了if-else语句。但是错误仍然存在!
任何帮助将不胜感激。
...
return (
<Grid container>
{enhancedSections.map((section, index) => {
<Conditional // this is line 182
path={section.conditional ? section.conditional.param_name : null }
section={section}
>
{() => {
if ( // these series of if-else statements renders perfectly without the <Conditional/> wrapper
section.style == "single_select" &&
section.section_display_name == selectedSection
) {
return (
<SingleSelect
key={section.definition.display_name}
displayName={section.definition.display_name}
description={
section.definition.description
? section.definition.description
: null
}
path={{ id: id, field: `${section.field}` }}
/>
);
} else if (
section.style == "boolean" &&
section.section_display_name == selectedSection
) {
return (
<Boolean
key={section.definition.display_name}
displayName={section.definition.display_name}
description={section.definition.description}
path={{ id: id, field: `${section.field}` }}
/>
);
} else if (
... // more conditional cmps here
)
}}
</Conditional>
})
}
</Grid>
);
<Conditional/>
的目的是仅在props.children
返回shouldRender()
时呈现其true
。
const Conditional = props => {
const shouldRender = path => {
if(!props.path){
return true;
}else{
return false
}
}
return (
shouldRender() ? props.children : null
);
}
export default Conditional;
提供给children
的Conditional
是function
。要渲染children as a function
(渲染道具),您应该像这样执行它
shouldRender() ? props.children() : null
children
是一个函数(为什么?)如果仍然希望子级成为函数,则只需调用children
。