reactjs - 打字稿声明合并原因是指一个值,但在反应中被用作类型
问题描述
我试图找到一种方法来避免绞尽脑汁想出一个名称,而不会因为 diff 声明和组件名称的后缀或前缀而破坏优雅。
我受到此链接的启发,避免在 TypeScript 中的对象和接口之间重复标识符 以使用声明合并。但似乎一切都在合并后一团糟。它既不检测类型也不检测值。
示例文件:
//Player.tsx
interface Player {
id: number
name: string
status: string
avatar: string
}
const Player: React.FC<Player> = ({name, status, avatar}) => (
<div className="flex">
<span className="block w-20 h-20 rounded-full bg-green-200">{avatar}</span>
<span className="pl-5 flex flex-col justify-center">
<p className="text-lg">{name}</p>
<p>{status}</p>
</span>
</div>
)
export default Player
这样,我得到了错误:
//ListPlayer.tsx
import Player from './Player';
export interface Props {
items: Player[] //'Player' refers to a value, but is being used as a type here. Did you mean 'typeof Player'?
}
const ListPlayer: React.FC<Props> = ({ items }) => (
<>
{items.map((item) => (
<Player {...item} />
))}
</>
);
export default ListPlayer;
如果我使用 typeof,上面的错误将被修复,但是,得到另一个错误:
//ListPlayer.tsx
import Player from './Player';
export interface Props {
items: typeof Player[]
}
const ListPlayer: React.FC<Props> = ({ items }) => (
<>
{items.map((item) => (
<Player {...item} /> //Type '{ propTypes?: WeakValidationMap<Player> | undefined; contextTypes?: ValidationMap<any> | undefined; defaultProps?: Partial<Player> | undefined; displayName?: string | undefined; }' is missing the following properties from type 'Player': id, name, status, avatarts(2739)
))}
</>
);
export default ListPlayer;
我想知道我的代码有什么问题?
解决方案
您将项目道具与 Player 组件混淆。
定义 PlayerProps 接口并导出:
import React from 'react'
export interface PlayerProps {
id: number
name: string
status: string
avatar: string
}
const Player: React.FC<PlayerProps> = ({name, status, avatar}) => (
<div className="flex">
<span className="block w-20 h-20 rounded-full bg-green-200">{avatar}</span>
<span className="pl-5 flex flex-col justify-center">
<p className="text-lg">{name}</p>
<p>{status}</p>
</span>
</div>
)
export default Player
对于 ListPlayer,您应该使用接口 PlayerPros 定义道具,如下所示:
import React from 'react'
import Player, {PlayerProps} from './Player';
export interface Props {
items: PlayerProps[]
}
const ListPlayer: React.FC<Props> = ({ items }) => (
<>
{items.map((item) => (
<Player {...item} />
))}
</>
);
export default ListPlayer;
推荐阅读
- javascript - 在第一个数组的每三个元素上组合对象数组
- python - 没有返回语句但不返回 None?
- php - 从嵌套字符串中提取 json 值的最佳方法是什么?
- jquery - 引导模型弹出窗口内的 DropDownList 在 asp.net core mvc 的编辑模式下不起作用
- c - 我的 C 程序未编译,未定义对“比较”的引用
- java - 如何将其他类值传递给 set 方法
- php - jquery的点击事件对我不起作用
- javascript - 如何比较和匹配`incomingArray`多维数组`task items and orders`与referenceArray匹配
- c++ - 在 vscode 中调试 c++ 代码时如何从用户那里获取输入
- python - Python split() 函数说明