我尝试有条件地渲染多个共享组件,但收到错误:
Line 182:9: Expected an assignment or function call and instead saw an expression 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;
最佳答案
提供给Conditional
的children
是一个函数
。要将子元素渲染为函数(渲染 Prop ),您应该像这样执行它
shouldRender() ? props.children() : null
关于javascript - React - Javascript 和 JSX 的条件渲染,条件包装组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58978541/