我正在尝试将 React DnD 与许多不同的可拖动元素(不同的形状等)一起使用。它们基本上都是相同的,并且具有相同的行为,因此我认为使用 HOC 是一个好主意。
我有以下 HOC,它是通过 React DnD 的可拖动组件:
import React, { Component } from "react";
import { DragSource } from "react-dnd";
// Components
import ItemTypes from "./ItemTypes";
/**
* Implements the drag source contract.
*/
const itemSource = {
beginDrag(props) {
return {};
}
};
/**
* Specifies the props to inject into your component.
*/
function collect(connect, monitor) {
return {
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging()
};
}
const DragItem = WrappedComponent => {
return class extends Component {
render() {
const { isDragging, connectDragSource } = this.props;
return connectDragSource(<WrappedComponent isDragging={isDragging} {...this.props} />);
}
};
};
export default DragSource(ItemTypes.BOX, itemSource, collect)(DragItem);
然后我就有了应该实现可拖动 HOC 的基本元素:
import React, { Component } from "react";
import DragItem from "../DragItem";
class Box extends Component {
render() {
return (
<div
style={{
height: "50px",
width: "50px",
background: "red"
}}
/>
);
}
}
export default DragItem(Box);
这是将它们联系在一起的 DnD 上下文:
import React, { Component } from "react";
import { DragDropContext } from "react-dnd";
import HTML5Backend from "react-dnd-html5-backend";
// Components
import DropContainer from "./dragNDropUploader/DropContainer";
import Box from "./dragNDropUploader/types/Box";
class UploadTest extends Component {
render() {
return (
<div className="body_container padded_top padded_bottom">
<DropContainer />
<Box />
</div>
);
}
}
export default DragDropContext(HTML5Backend)(UploadTest);
我在开发工具控制台中收到以下内容:react.development.js:233 Uncaught TypeError: Cannot set property 'props' of undefined
我不完全确定我做错了什么。如果我从 DragItem
HOC 中删除 DnD 内容,内容将按预期显示(但当然不可拖动)。但如果我尝试像我一样实现 DnD,它就会崩溃并消失。
请教我:)
最佳答案
这就是我定义可拖动组件的 render()
的方式...
return (
<div
onClick={(e) => this.handleClick(e)}
onDragStart={(e) => this.handleDragStart(e)}
onDrop={(e) => this.handleDragDrop(e)}
onDragEnter={(e) => this.handleDragEnter(e)}
onDragOver={(e) => this.handleDragOver(e)}
onDragLeave={(e) => this.handleDragLeave(e)}
draggable={true}
>Draggable Div</div>
);
对于所有这些的 ReactJS 处理程序,具有以下内容:
handleDragEnter(e) {
e.preventDefault();
e.stopPropagation();
return false;
}
handleDragStart(e)
处理程序除外,它不会取消事件或返回 false。您可以将任何类型的逻辑放入任何处理程序中。
这种“杀伤力”很大程度上是因为各种浏览器处理拖放的方式不同,例如,如果您在 Chrome 中将元素 A 拖到元素 B 上,则可能不会发生任何事情,but in Firefox, it will try to open element A as though it were a file.
我在 npm 等尝试过的软件包中有一半以上根本不起作用。人们必须像下载 SourceForge 项目一样对待 NPM 包——几乎 100% 保证所有功能都能完美运行。因此,我不确定您下载的特定 HOC 有什么问题,但我希望这 10 行代码与您发布的 3 页一样容易理解。
关于javascript - 使用 HOC 可拖动元素 react DnD 抛出 Cannot set property 'props' of undefined 错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51217081/