你好,我想做的只是一个简单的条件渲染,我之前在 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,但在这里我收到一条错误消息,提示“预期表达式”,我认为这是 typescript 错误,但我不知道为什么它不让我使用 if那里。任何人都可以向我解释为什么以及是否有办法做我想做的事?
最佳答案
在 JavaScript 中(因此在 TypeScript 中也是如此),有表达式和语句。您可以将表达式用作语句,但反之则不行。
if
是一个语句,但 JSX 的大括号只需要表达式。进行条件渲染的正确方法是使用 &&
:
{this.props.showEntryDetails && (
<tr>
<td>"Hello"</td>
</tr>
)}
关于typescript - Preact/typeScript 条件渲染 "expression expected",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53609606/