如何使每个项目都是可拖放的?
当map()
函数返回新数组时,我决定将connectDragSource
传递到方法中,但是我仍然返回可投放的Aray 插入的可投放的每个项目(形状)
for..in
,forEach
,for..of
也无法获得期望的结果
有人解决了这个问题吗?
import React, { Component } from "react";
import { Segment, Icon } from "semantic-ui-react";
import { DragSource } from "react-dnd";
import ShapeItem from "./ShapeItem";
class Shapes extends Component {
displayShapes = (shapes, connectDragSource) =>
shapes.length > 0 &&
shapes.map((shape) =>
connectDragSource(
<div key={shape.id}>
<Segment>
<Icon name={shape.name} size={shape.size} color={shape.color} />
</Segment>
</div>
)
);
render() {
const { shapes, connectDragSource} = this.props;
return (
<div>
{this.displayShapes(shapes, connectDragSource)}
</div>
);
}
}
const spec = {
beginDrag(props) {
return {
shapeId: props.shapes.id
};
}
};
const collect = (connect, monitor) => ({
connectDragSource: connect.dragSource(spec),
isDragging: monitor.isDragging()
});
export default DragSource("shape", spec, collect)(Shapes);
对于文档http://react-dnd.github.io,仅发现以下内容:将元素作为可拖动节点。为此,请在呈现函数中用element
替换任何this.props.connectDragSource(element)
。
答案 0 :(得分:1)
您可能想要创建一个单独的组件来渲染每个项目并将其作为拖动源。您还需要从规范中的canDrag函数返回true。
免责声明:我尚未测试以下代码。
shapes.js
import React, { Component } from "react";
import Item from './item.js';
class Shapes extends Component {
render() {
const { shapes } = this.props;
return (
<div>
{
shapes.length > 0 &&
shapes.map((shape) => <Item key={shape.id} shape={shape} />)
}
</div>
);
}
}
export default Shapes;
item.js
import React, { Component } from "react";
import { Segment, Icon } from "semantic-ui-react";
import { DragSource } from "react-dnd";
class Item extends Component {
render() {
const { shape, connectDragSource} = this.props;
return connectDragSource(
<div>
<Segment>
<Icon name={shape.name} size={shape.size} color={shape.color} />
</Segment>
</div>
)
}
}
const spec = {
beginDrag(props) {
return {
shapeId: props.shapes.id
};
},
canDrag(props, monitor) {
return true;
},
endDrag(props, monitor) {
console.log("You dropped .... into " + monitor.getDropResult());
}
};
const collect = (connect, monitor) => ({
connectDragSource: connect.dragSource(spec),
isDragging: monitor.isDragging()
});
export default DragSource("shape", spec, collect)(Item);