在打字稿文件中提供以下React功能组件:
Cell.tsx:
import React from 'react'
interface CellProps {
row: number
cell: number
handleClick: (row: number, cell: number) => void
}
export const Cell: React.FC<CellProps> = ({ row, cell, handleClick}) => {
const onClick = (e: React.FormEvent<HTMLDivElement>) => {
e.preventDefault()
console.log(row, cell);
handleClick(row, cell)
}
return (
<td onClick={onClick}>Cell</td>
)
}
并给出以下需要它的React功能组件:
Game.tsx:
import React from 'react'
import { Cell } from './Cell'
interface GameProps {
height: number
width: number
}
export const Game: React.FC<GameProps> = ({height, width}) => {
const handleClick = (row: number, col: number) => {
console.log("Game.handleClick called...");
}
// Typescript doesn't like this. What am I doing wrong here?
let cells: Array<Cell> = new Array<Cell>()
// Typescript is ok with this, so what am I doing wrong in the line above?
let cols: Array<{}> = new Array<{}>()
return <table>
<tbody>
<tr>
<Cell row={0} cell={0} handleClick={handleClick} />
</tr>
</tbody>
</table>
}
[尝试创建Game.tsx
组件数组时,Cell
出现错误:
'Cell' refers to a value, but is being used as a type here. TS2749
下面的行很好(我将数组键入为空Object
),所以我在做什么错呢?如何创建Cells
的空数组,以便可以在渲染部分中像{cells}
那样调用它们?
发生错误,是因为您尝试使用Cell.tsx中定义为“ Cell”的函数作为类型。如果为Cell函数定义显式类型定义,则可以解决此问题:
import React from 'react'
interface CellProps {
row: number
cell: number
handleClick: (row: number, cell: number) => void
}
export type cellType = (args: CellProps) => React.FC<CellProps>;
export const Cell:cellType = ({ row, cell, handleClick}) => {
const onClick = (e: React.FormEvent<HTMLDivElement>) => {
e.preventDefault()
console.log(row, cell);
handleClick(row, cell)
}
return (
<td onClick={onClick}>Cell</td>
)
}
然后您可以在Game.tsx中导入类型,并使用它来定义单元格数组。