React DND connect.dragTarget: Drag and Drop Components with Ease
The connect.dragTarget is a function provided by the react-dnd library in React. It is used to create a higher-order component (HOC) that can be used to connect a React component to the drag source in a drag and drop operation.
Here's an example usage of connect.dragTarget:
import { useDrag, DragSourceMonitor } from 'react-dnd';
import { ItemTypes } from './ItemTypes';
const MyComponent = ({ isDragging, connectDragSource }) => {
const [{ opacity }, drag] = useDrag({
item: { type: ItemTypes.BOX },
collect: (monitor) => ({
opacity: monitor.isDragging() ? 0.4 : 1,
}),
});
return (
<div ref={drag} style={{ opacity }}>
Drag me!
</div>
);
};
export default connect.dragTarget(
(connect, monitor) => ({
connectDragSource: connect.dragSource(),
isDragging: monitor.isDragging(),
}),
)(MyComponent);
In this example, useDrag hook is used to define the drag source behavior of the component. The connect.dragSource() function is then used within connect.dragTarget to connect the drag source to the component. This allows the component to be draggable and provides the necessary props (isDragging and connectDragSource) to control the drag behavior and appearance of the component.
Note: The example usage above assumes the usage of React Hooks API. If you are not using hooks, you can use the HOC syntax provided by react-dnd instead.
原文地址: https://www.cveoy.top/t/topic/pzSP 著作权归作者所有。请勿转载和采集!