React-dnd: 如何根据实际拖动的元素调整预览大小?

创建于 2016-04-20  ·  6评论  ·  资料来源: react-dnd/react-dnd

我有一个可拖动的文本,但我想显示该文本的宽度/高度等于其实际大小的 20% 左右。 我想知道我应该如何调整将任何样式应用于预览屏幕截图的大小。 我不知道如何定位屏幕截图本身。 有什么办法吗?

triage wontfix

最有用的评论

您可以通过监视器项目实现这一点。

beginDrag的 DragSource 规范中,它用于定义监视器项目,您将反应组件实例作为第三个参数并将其添加到项目中。 稍后,通过使用findDOMNode可以获得实际节点。

因此,首先将组件实例添加到项目中。

  beginDrag({ id }, monitor, component) {
    return {
      id,
      component
    };
  },

稍后在 DragLayer 中,您需要该项目。

const CustomDragLayer = DragLayer(monitor => ({
  item: monitor.getItem(),
  isDragging: monitor.isDragging() // useful
}))(CustomDragLayer);

现在在 CustomDragLayer 道具中,您将收到具有组件的项目。

class CustomDragLayer extends Component {
  constructor(props) {
    super(props);
    this.width;
    this.height;

    // Now you can eacily get height or width from node 
    const node = findDOMNode(props.item.component);
    console.log(node.clientWidth);
  }
...

注意findDOMNode是如何在constructor ,它可能不会在render并且在大多数情况下没有实际需要,Drag Source 可能具有静态大小。

所有6条评论

查看 DragLayer 的文档(http://gaearon.github.io/react-dnd/examples-drag-around-custom-drag-layer.html)

嘿,我有一个类似的问题 - 想要为拖动预览提供一个图像,并且反应 dnd 使它太大了 - 在传递给 connectDragPreview 之前,我尝试使用宽度/高度和 style.w/h 设置图像大小,但没有任何效果。 梳理了文档并找不到任何关于调整预览图像大小的提及。 在这种情况下,显示图像的实际 html 元素深埋在库组件中,因此也不容易访问,因此最直接的解决方案是如果 connectDragPreview/dragPreview 可以公开调整大小选项(或者甚至更好地尊重传入的图像)。

这是一些非工作代码 - 无论是在 onload 函数还是在 setDragImage 函数中,设置图像宽度和高度都没有效果:

componentDidMount = () => {
this.setDragImage();
};

componentDidUpdate = () => {
this.setDragImage();
};

setDragImage = () => {
const image = new Image();
image.src = this.props.imgUrl;
image.onload = () => {
image.width = image.height = 35;
this.props.connectDragPreview(image);
}
};

关于这个问题的任何更新?

您可以通过监视器项目实现这一点。

beginDrag的 DragSource 规范中,它用于定义监视器项目,您将反应组件实例作为第三个参数并将其添加到项目中。 稍后,通过使用findDOMNode可以获得实际节点。

因此,首先将组件实例添加到项目中。

  beginDrag({ id }, monitor, component) {
    return {
      id,
      component
    };
  },

稍后在 DragLayer 中,您需要该项目。

const CustomDragLayer = DragLayer(monitor => ({
  item: monitor.getItem(),
  isDragging: monitor.isDragging() // useful
}))(CustomDragLayer);

现在在 CustomDragLayer 道具中,您将收到具有组件的项目。

class CustomDragLayer extends Component {
  constructor(props) {
    super(props);
    this.width;
    this.height;

    // Now you can eacily get height or width from node 
    const node = findDOMNode(props.item.component);
    console.log(node.clientWidth);
  }
...

注意findDOMNode是如何在constructor ,它可能不会在render并且在大多数情况下没有实际需要,Drag Source 可能具有静态大小。

@MrBr ,谢谢它的工作。

此问题已自动标记为过时,因为它最近没有活动。 如果没有进一步的活动发生,它将被关闭。 感谢你的贡献。

此页面是否有帮助?
0 / 5 - 0 等级