首页 > 解决方案 > Preact/typeScript 条件渲染“预期表达式”

问题描述

你好,我想做的只是一个简单的条件渲染,我之前在 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 但在这里我收到一条错误消息“预期表达式”我认为这是一个打字稿错误但我不知道为什么它不会让我有一个 if 存在。谁能向我解释为什么以及是否有办法做我想做的事?

标签: typescriptpreactconditional-rendering

解决方案


在 JavaScript 中(TypeScript 也是如此),有表达式和语句。您可以将表达式用作语句,但反之则不行。

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

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

推荐阅读