【发布时间】:2019-06-27 11:23:58
【问题描述】:
我有一个通过数组映射的反应组件。
每个数组项都有一个可选的 ID 类型。
如果我有这个ID,我会渲染一个元素,否则什么都不会。
这个元素有一个 onClick,它调用一个接受 ID 作为参数的函数。
即使我检查我是否有 ID,TypeScript 仍然抱怨 ID 可能未定义,但仅限于 onClick 方法内部,而不是外部(参见代码示例)
这是为什么呢?我怎样才能让这个错误消失?
Please see the error on the TypeScript playground:
// fake bindings
declare namespace React {
function createElement(): any;
}
// This type has an optional prop
type SampleType = {
id?: string;
name: string;
}
const sampleArray: SampleType[] = [{id: 'test', name: 'Adrian'}, {name: 'Florescu'}]
function sampleFunction(id: string){
console.log('ID', id);
}
function SampleComponent() {
return (
<div>
{sampleArray.map((item: SampleType) => {
if(item.id) {
sampleFunction(item.id); // This works
return <p onClick={() => { sampleFunction(item.id); }}>{item.name}</p>; //// This does not work
}
})}
</div>
)
};
const dom = <SampleComponent />;
【问题讨论】:
-
当您发布问题时,我注意到您发布了 TypeScript 游乐场链接“原始”(因此它既是链接又是文本)。我编辑使它只是一个带有文本标签的链接,它坏了。我设法修复它,但不明白为什么它坏了。我有found the answer。之所以提到它,是因为现在,如果你想链接到 TypeScript 的新游乐场,你需要做这个解决方法。
标签: javascript reactjs typescript