我正在使用带有react-beautiful-dnd库的TypeScript(当然还有React),但我似乎无法解决这个错误:
[ts] JSX元素类型'DragDropContext'不是构造函数 对于JSX元素。属性“render”的类型是不兼容的。 输入'()=> ReactNode'不能赋值为'{():ReactNode; ():false |元件; }”。 类型'ReactNode'不能赋值为'false |元件'。 类型'string'不能赋值为'false |元素”
我已经查看并复制了几个示例,试图弄清楚为什么会出现这个错误并且我出现了空白。
这是我的代码,其中大部分是直接从文档中复制的,作为测试:
import * as React from 'react';
import {Component} from 'react';
import { DragDropContext, Droppable, Draggable } from 'react-beautiful-dnd';
interface Item {
id: string,
content: string,
}
interface TodoListProps extends React.Props<TodoList> {
}
interface TodoListState {
items: Item[]
}
const getItemStyle = (draggableStyle:any, isDragging: boolean): Object => ({
// some basic styles to make the items look a bit nicer
userSelect: 'none',
padding: 8 * 2,
// change background colour if dragging
background: isDragging ? 'lightgreen' : 'grey',
// styles we need to apply on draggables
...draggableStyle,
margin: draggableStyle && draggableStyle.margin ? draggableStyle.margin : `0 0 ${8}px 0`,
});
const getListStyle = (isDraggingOver:boolean) => ({
background: isDraggingOver ? 'lightblue' : 'lightgrey',
padding: 8,
width: 250
});
// a little function to help us with reordering the result
const reorder = (list:any[], startIndex:number, endIndex:number) => {
const result = Array.from(list);
const [removed] = result.splice(startIndex, 1);
result.splice(endIndex, 0, removed);
return result;
};
export default class TodoList extends React.Component<{},TodoListState>{
private constructor(props:any){
super(props);
this.state = {
items: [
{id: "0", content: 'Hello'}
]
}
}
componentDidMount(){
}
onDragEnd = (result: any) => {
// dropped outside the list
if (!result.destination) {
return;
}
const items = reorder(
this.state.items,
result.source.index,
result.destination.index
);
this.setState({
items
});
}
render() {
return (
<DragDropContext onDragEnd={this.onDragEnd}>
<Droppable droppableId='droppable'>
{(dropProvided, snapshot) => (
<div
ref={dropProvided.innerRef}
style={getListStyle(snapshot.isDraggingOver)}
>
{this.state.items.map(item => (
<Draggable key={item.id} draggableId={item.id}>
{(provided, snapshot) => (
<div>
<div
ref={provided.innerRef}
style={getItemStyle(
provided.draggableStyle,
snapshot.isDragging
)}
{...provided.dragHandleProps}
>
{item.content}
</div>
{provided.placeholder}
</div>
)}
</Draggable>
))}
</div>
)}
</Droppable>
</DragDropContext>
);
}
}
如果我无法解决错误,我可以告诉TypeScript忽略某些jsx错误吗?
更新
我通过从package.json中删除我的锁文件,我的node_modules文件夹和所有依赖项来修复此问题。我再次使用npm重新安装了所有内容,它开始工作了。一定是版本不匹配的地方。
感谢所有花时间观看和评论的人!