打字稿:扩展 div 元素的属性在反应引用上失败



我正在处理一个带有 react-beautiful-dnd 的拖放场景,尝试按照手动 https://github.com/atlassian/react-beautiful-dnd/blob/master/docs/guides/drop-animation.md 添加拖放动画。

使用打字稿,当我将isDragging属性添加到简单的div 元素时,我遇到了麻烦。试图解决此问题,我正在构建一个具有扩展属性的组件,如下所示

在 Typescript React 应用程序中指定特定的道具并接受通用的 HTML 道具

这在某种程度上有效,但在 ref 属性上失败。

我的代码:

interface IdragDiv extends React.HTMLAttributes<HTMLDivElement>, React.RefAttributes<HTMLDivElement> {
isDragging: boolean;
}
export class DragDiv extends React.Component<IdragDiv> {
render() {
const { children, ...rest } = this.props;
return <div {...rest}>{children}</div>;
}
}

这样称呼它:

...
return (
<Draggable
draggableId={...}
>
{(provided, snapshot) => {
return (
<DragDiv
{...className}
ref={provided.innerRef}
{...provided!.draggableProps}
{...provided!.dragHandleProps}
isDragging={snapshot.isDragging && !snapshot.isDropAnimating}
>
...
</DragDiv>
);
}}
</Draggable>
);
...

这会导致以下错误:

(property) ref?: (string & ((instance: HTMLDivElement | null) => void)) | (string & React.RefObject<HTMLDivElement>) | (((instance: DragDiv | null) => void) & ((instance: HTMLDivElement | null) => void)) | ... 4 more ... | undefined
No overload matches this call.
Overload 1 of 2, '(props: Readonly<IdragDiv>): DragDiv', gave the following error.
Type '(element?: HTMLElement | null | undefined) => any' is not assignable to type '(string & ((instance: HTMLDivElement | null) => void)) | (string & RefObject<HTMLDivElement>) | (((instance: DragDiv | null) => void) & ((instance: HTMLDivElement | null) => void)) | ... 4 more ... | undefined'.
Type '(element?: HTMLElement | null | undefined) => any' is not assignable to type 'string & ((instance: HTMLDivElement | null) => void)'.
Type '(element?: HTMLElement | null | undefined) => any' is not assignable to type 'string'.
Overload 2 of 2, '(props: IdragDiv, context?: any): DragDiv', gave the following error.
Type '(element?: HTMLElement | null | undefined) => any' is not assignable to type '(string & ((instance: HTMLDivElement | null) => void)) | (string & RefObject<HTMLDivElement>) | (((instance: DragDiv | null) => void) & ((instance: HTMLDivElement | null) => void)) | ... 4 more ... | undefined'.
Type '(element?: HTMLElement | null | undefined) => any' is not assignable to type 'string & ((instance: HTMLDivElement | null) => void)'.
Type '(element?: HTMLElement | null | undefined) => any' is not assignable to type 'string'.

任何想法,有没有其他方法可以解决这个问题?

你应该能够在代码中使用createRef((,如下所示:

class Foo extends Component {
private myRef = createRef<HTMLDivElement>();
render() {
return <div ref={this.myRef} />
}
}

这是简化的ofc,但这应该可以解决您遇到的错误。

可能这将修复它 react-beautiful-dnd 然后,通过为您拥有的 DragDiv 创建您自己的 ref 道具:

class DragDiv extends React.Component {
render() {
return (
<div {...this.props} ref={this.props.innerRef}></div>
);
}
}

然后在您的可拖动对象中:

return (
<Draggable draggableId={...}>
{(provided, snapshot) => {
return (
<DragDiv
{...className}
innerRef={provided.innerRef}
...

看看这是否为您解决了它。

最新更新