reactjs - 反应打字稿错误类型'{ id:数字;标题:字符串;函数():无效;}' 不可分配给类型 'null'
问题描述
我按照本教程尝试重新创建具有活动打开和关闭状态的按钮组,但是在使用打字稿时出现以下错误:
Type '{ id: number; title: string; function(): void; }' is not assignable to type 'null'.
代码:
import React from 'react';
import Button from '../button/Button'
const ButtonGroup: React.FunctionComponent = () => {
const [active, setActive] = React.useState({
activeObject: null,
objects: [{
id: 1 as number,
title: '1' as string,
function() {
alert('yes 1')
}
}, {
id: 2 as number,
title: '2' as string,
function() {
alert('yes 2')
}
}, {
id: 3 as number,
title: '3' as string,
function() {
alert('yes 3')
}
}]
})
const toggleActive = (index: number) => {
setActive({ ...active, activeObject: active.objects[index] })
}
function toggleActiveStyles(index: number) {
if (active.objects[index] === active.activeObject) {
return "btn-tertiary"
} else {
return "btn-tertiary-active"
}
}
return (
<> <div >
{active.objects.map((inner, index) => {
return (
<Button variant="btn btn-tertiary" className={toggleActiveStyles(index)} onClick={() => toggleActive(index)} key={inner.id}>{inner.title}</Button>
)
})}
</div>
</>
)
}
export default ButtonGroup;
有任何想法吗?
解决方案
useState
如果您不直接指定,将默认为参数的“类型”。
const [active, setActive] = React.useState({
activeObject: null,
/* ... */
});
所以在这种情况下,activeObject
只能推断为存在null
而没有别的。
相反,我建议定义一个type
orinterface
并告诉useState
它是状态对象的类型。
type AO = {
activeObject: { id: number; title: string; function(): void; };
/* and all of your other data */
}
然后
const [active, setActive] = React.useState<AO>({ /* ... */ });
将指定它active
的类型是AO
. 然后,您也不需要执行as number
or as string
,因为这些类型将被要求为AO
类型。
推荐阅读
- machine-learning - XGBoost 超参数调优
- c# - 删除/保护 url 中的 id 不被篡改
- c# - 如何构建此决策树?
- javascript - 带有承诺的jquery多个http get请求
- javascript - 如何在不重新加载整个页面的情况下重新加载 Next.js 页面初始道具
- javascript - 当应用程序托管在 Heroku (Node.js) 上时,无法连接到 Websocket
- c++ - 将模板(没有规范)传递给 std::thread() 会产生错误:
匹配错误 - python - Pandas groupby 变换('mean')skipna=False
- r - Shiny中highcharter的重音字符编码问题
- php - 响应式文件管理器上传带有灰色条和多个空版本的图像