【问题标题】:React Typescript 101: Using Typescript with const list and functionReact Typescript 101:将 Typescript 与 const 列表和函数一起使用
【发布时间】:2022-01-05 09:18:27
【问题描述】:

很抱歉,我将如何在下面的示例中使用 typescript。经过一个小时的尝试,感谢您的帮助!

下面的 map 函数使用了 sortOptions,我尝试在声明 const SortOptionsProps 时使用 Typescript 定义它们。因此,我很想弄清楚如何将 SortOptionsProps 传递给下面的export default function Layout()

import { Menu } from '@headlessui/react'

declare const SortOptionsProps: {
    name: string
    href: string
}[]

const sortOptions = [
    { name: 'Most Popular', href: '#' },
    { name: 'Best Rating', href: '#' },
    { name: 'Newest', href: '#' },
    { name: 'Price: Low to High', href: '#' },
    { name: 'Price: High to Low', href: '#' },
]

export default function Layout() {
    return (
        <>
        {sortOptions.map((option) => (
            <Menu.Item key={option}>
                {({ active }) => (
                    <a
                        href={option.href}
                        className={classNames(
                            active
                                ? 'bg-gray-100'
                                : '',
                            'block px-4 py-2 text-sm font-medium text-gray-900'
                        )}
                    >
                        {option.name}
                    </a>
                )}
            </Menu.Item>
        ))}      
    </>
    )
}

【问题讨论】:

标签: reactjs typescript


【解决方案1】:
type SortOption = { name: string; href: string }:

const sortOptions: SortOption[] = [
    { name: 'Most Popular', href: '#' },
    { name: 'Best Rating', href: '#' },
    { name: 'Newest', href: '#' },
    { name: 'Price: Low to High', href: '#' },
    { name: 'Price: High to Low', href: '#' },
]

如果您愿意,也可以使用interface 代替type

interface SortOption { name: string; href: string }

【讨论】:

    猜你喜欢
    • 2021-12-27
    • 2020-08-06
    • 2021-04-03
    • 2019-07-30
    • 1970-01-01
    • 1970-01-01
    • 2019-10-11
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多