Preact/typeScript 条件渲染"expression expected"



你好,我只想做一个简单的条件渲染,我以前在react中做过,但在preact中似乎做不到。

export const InfoSection = (props: Props) => 
{
return (
<div>
<table>
<tr>
<th>#</th>
<th>User</th>
<th>Info</th>
<th>date</th>
</tr>
{
props.infoEntries.map( (l, i) => 
{
return (
<tr>
<td>{i+1}</td>
<td{l.UserId}</td>
<td>{l.Info}</td>
<td>{l.Date}</td>
</tr>
)
})
}
{
if(this.props.showEntryDetails){
return(
<tr>
<td>"Hello"</td>
</tr>
)
}
}
</table>
</div>
)
}

正如你在底部看到的,我只是试图在showEntryDetails上使用if,但这里我得到了一个错误,说"Expression Expected"。我认为这是一个打字错误,但我不知道为什么它不让我有if。有谁能向我解释为什么,如果有办法做我想做的事?

在JavaScript中(因此在TypeScript中也是如此(,有表达式和语句。可以将表达式用作语句,但不能将其用作语句。

if是一个语句,但JSX的花括号只需要表达式。进行条件渲染的正确方法是使用&&:

{this.props.showEntryDetails && (
<tr>
<td>"Hello"</td>
</tr>
)}

最新更新