我将React与Typescript一起使用,并尝试基于react-dnd库创建一个更高阶的组件。该错误发生在react-dnd组件的DragSource部分中。这是对应的代码:
import React from 'react';
import { DragSource, ConnectDragSource, DragSourceConnector, DragSourceMonitor } from 'react-dnd';
import ItemTypes from './itemTypes'
const collect = (connect: DragSourceConnector, monitor: DragSourceMonitor) => {
return {
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
}
}
const templateObjectSource = {
beginDrag(props: any) {
return {}
}
}
export interface TemplateObjectCollectedProps {
canDrop: boolean
isOver: boolean
connectDragSource: ConnectDragSource
}
export interface TemplateObjectProps {
name?: string
}
function withTemplateObjectDraggable(WrappedComponent: React.ComponentClass<TemplateObjectProps>) {
return class WithTemplateObjectDraggable extends React.Component<TemplateObjectCollectedProps> {
public render() {
return this.props.connectDragSource(
<div>
<WrappedComponent {...this.props} />
</div>
)
}
}
}
export default DragSource(ItemTypes.TEXTFIELD, templateObjectSource, collect)(withTemplateObjectDraggable)
Typescript在最后一行给我以下错误,特别是在[(withTemplateObjectDraggable)“部分:
[ts]
Argument of type '(WrappedComponent: ComponentClass<TemplateObjectProps, any>) => typeof WithTemplateObjectDraggable' is not assignable to parameter of type 'ComponentType<ComponentClass<TemplateObjectProps, any>>'.
Type '(WrappedComponent: ComponentClass<TemplateObjectProps, any>) => typeof WithTemplateObjectDraggable' is not assignable to type 'FunctionComponent<ComponentClass<TemplateObjectProps, any>>'.
Type 'typeof WithTemplateObjectDraggable' is not assignable to type 'ReactElement<any>'.
Property 'type' is missing in type 'typeof WithTemplateObjectDraggable'. [2345]
我不确定我是在错误地使用高阶组件,还是只是一个类型主题。不幸的是,我没有找到一个将react-dnd与其他高阶组件结合在一起的示例,因此可能是我走错了路。如果您可以向我提供一个有效的打字稿(或javascript)示例的链接,它将为我提供帮助,该示例在react-dnd的“ DragSource”之上实现了一个更高阶的组件,因为我找不到一个。
仅供参考:然后我将使用像这样的高阶组件:
import React from 'react';
import imgTextfield from '../../../../../assets/templateObjects/textfield.png'
import withTemplateObjectDraggable from './withTemplateObjectDraggable'
class Textfield extends React.Component {
public render() {
return (
<span>
<img src={imgTextfield} />
<div> Textfield </div>
</span>
)
}
}
export default withTemplateObjectDraggable(Textfield)
答案 0 :(得分:1)
看来您的逻辑有些错误。 RestTemplate
期望将React组件作为输入,但是您正在尝试传递DragSource
HOC。因此,Typescript抱怨类型不兼容。
我不确定100%是否会起作用,但是尝试像这样:在您的HOC内部移动withTemplateObjectDraggable
:
DragSource