Preact/typeScript 条件渲染 "expression expected"
Preact/typeScript conditional rendering "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" 我认为这是打字稿错误,但我不知道为什么它不允许我这样做如果有的话。任何人都可以向我解释为什么以及是否有办法做我想做的事?
在 JavaScript 中(因此在 TypeScript 中也是如此),有表达式和语句。您可以将表达式用作语句,但反之则不行。
if
是一个语句,但 JSX 的大括号只需要表达式。进行条件渲染的正确方法是使用 &&
:
{this.props.showEntryDetails && (
<tr>
<td>"Hello"</td>
</tr>
)}
你好,我只想做一个简单的条件渲染,我之前在 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" 我认为这是打字稿错误,但我不知道为什么它不允许我这样做如果有的话。任何人都可以向我解释为什么以及是否有办法做我想做的事?
在 JavaScript 中(因此在 TypeScript 中也是如此),有表达式和语句。您可以将表达式用作语句,但反之则不行。
if
是一个语句,但 JSX 的大括号只需要表达式。进行条件渲染的正确方法是使用 &&
:
{this.props.showEntryDetails && (
<tr>
<td>"Hello"</td>
</tr>
)}