【发布时间】:2021-06-16 04:56:03
【问题描述】:
如果某些条件为真,我想返回 jsx,如果不应该返回 undefined。
下面是我的代码,
const showInfo = (item) {
return (
<div>
<div>
<span>name</span>
</div>
<div>
<button>click</button>
</div>
</div>
);
}
const Parent = () => {
return (
<Child
onDone = {({item}) => {
notify ({
actions: (condition === 'value1' || condition === 'value2' ) &&
showInfo(item) //should put this condition into showInfo method
})
}}
/>
);
}
我想做什么? 上面的代码有效。但现在我想将条件放在 showInfo 方法中。所以如果条件为真则返回 jsx,如果条件为假则返回 undefined。
我尝试了什么? 我尝试过类似下面的方法
const showInfo = (item) {
return
{(condition === 'value1' || condition === 'value2' ) ? <div>
<div>
<span>name</span>
</div>
<div>
<button>click</button>
</div>
</div>
: undefined
}
);
}
const Parent = () => {
return (
<Child
onDone = {({item}) => {
notify ({
actions: showInfo(item) //error here
})
}}
/>
);
}
但上面尝试过的代码在操作语句中给出错误“类型'void'不可分配给类型'ReactNode'”。
有人可以帮我解决这个问题吗?我不确定我是否正确使用了三元运算符。谢谢。
编辑
在尝试提供的答案之一后,
notify 是一个从 usehook 返回的方法 它评估为下面的组件
const Something: React.FC<SomethingProps> = ({
description,
actions,
...props
}) =>
(
<Header>
<Title>{title}</Title>
</Header>
{(description ||actions) && (
<Body> //this is displayed
{description && <Description>{description}</Description>}
{actions && <Actions>{actions}</Actions>}
</Body>
)}
);
这里是showInfo组件条件失败时显示的组件。
在 showInfo 中,如果条件失败,我将返回 undefined,但仍然在 Something 组件中显示,即使我有 {description ||行动}
我不确定这里发生了什么。我必须检查在这种情况下不显示的操作的条件是什么
我试过了
{(description ||actions !== 'false') && (
<Body> //this is displayed
{description && <Description>{description}</Description>}
{actions && <Actions>{actions}</Actions>}
</Body>
)}
这行得通。我想知道为什么我应该特别提到
actions !== 'false'
而不仅仅是动作 有人可以帮我解决这个问题。谢谢。
【问题讨论】:
-
您在返回后的 showInfo 函数中缺少左括号
(。 -
只需使用
: null而不是: undefined
标签: javascript reactjs