我有以下两个组件:
DraggableGameStart
import DraggableGameAnswers from './DraggableGameAnswers';
import { useRef } from 'react';
function DraggableGameStart() {
const draggableGame = useRef<HTMLDivElement>(null);
return (
<div className="draggable-game-content">
<div className="draggable-game" ref={draggableGame}>
<DraggableGameAnswers elementBounds={draggableGame}/>
</div>
</div>
</div>
);
}
export default DraggableGameStart;和DraggableGameAnswers
import { RefObject } from 'react';
import { useEffect } from 'react';
type DraggableGameAnswersProps = {
elementBounds: RefObject<HTMLDivElement>
}
function DraggableGameAnswers(props: DraggableGameAnswersProps) {
let boundsArray: Array<number>[];
useEffect(
() =>
boundsArray.push(props.elementBounds.current?.getBoundingClientRect().top)
)
return (
<div className="draggable-game-answers">
test
</div>
);
}
export default DraggableGameAnswers;但是我得到了一些错误:
Type number is not assignable to type 'void | Destructor' ;
Argument of type 'number | undefined' is not assignable to parameter of type 'number[]'.
Type 'undefined' is not assignable to type 'number[]'.我真的不明白为什么。
为什么会抛出这些错误,我如何修复它们?
编辑:
我根据一条评论改成了这行
let boundsArray: Array<number>;什么都没有改变,只是第二个错误变成了这样:
Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
Type 'undefined' is not assignable to type 'number'.发布于 2021-11-09 22:40:33
此错误对于您阅读和理解此错误非常重要。
Argument of type 'number | undefined' is not assignable to parameter of type 'number'.
Type 'undefined' is not assignable to type 'number'.你会注意到这个值:
props.elementBounds.current?.getBoundingClientRect().top并不总是一个数字。如果current属性为undefined,那么您将获得undefined。这就是为什么这个值的类型是number | undefined。
你把它推送到一个不接受undefined的number数组中,所以你会得到这个错误。
要修复它,您只需在将其推送到数组之前检查该值是否不是null或undefined。
let boundsArray: Array<number>;
useEffect(() => {
const value = props.elementBounds.current?.getBoundingClientRect().top
if (value != null) {
boundsArray.push(value) // works
}
}) 发布于 2021-11-09 21:57:04
这个错误通常意味着你正在传递一个不适合你为组件定义的typescript接口的属性。我认为在这种情况下你要找的是转发的ref,而不是传递一个普通的道具。它可能看起来像这样:
import { React, useEffect } from 'react';
const DraggableGameAnswers = React.forwardRef((props, ref) {
let boundsArray: Array<number>[];
useEffect(
() =>
boundsArray.push(ref.current?.getBoundingClientRect().top)
)
return (
<div className="draggable-game-answers">
test
</div>
);
})
export default DraggableGameAnswers;然后,如果它不能解决问题,那么像<DraggableGameAnswers ref={draggableGame}/>这样调用它至少可以为您指明一个不同的方向。
https://stackoverflow.com/questions/69905223
复制相似问题