react-draggable不适用于自定义组件

时间:2019-02-11 22:54:40

标签: javascript reactjs

https://github.com/mzabriskie/react-draggable

如何获取自定义组件以进行拖动?

点击以下内容即可

import React from 'react';
import { DraggableCore } from 'react-draggable';

export default class Hello extends React.Component {

  onStart = () => {
    console.log('here');
  }

  render() {
    return (
      <DraggableCore
        onStart={this.onStart}
      >
        <h1>Drag me!</h1>
      </DraggableCore>
    );
  }
}

这不是

import React from 'react';
import { DraggableCore } from 'react-draggable';

class Test extends React.Component {
  render() {
    return (
      <h1>{this.props.children}</h1>
    );
  }
}

export default class Hello extends React.Component {

  onStart = () => {
    console.log('here');
  }

  render() {
    return (
      <DraggableCore
        onStart={this.onStart}
      >
        <Test>Drag me!</Test>
      </DraggableCore>
    );
  }
}

唯一的区别在于,它现在使用自定义组件h1来代替直接使用Test

https://stackblitz.com/edit/react-ev9iyu?file=Hello.js

我尝试转发参考。我也尝试过将其包装在Fragment

2 个答案:

答案 0 :(得分:1)

div内部用DraggableCore包装组件:

<DraggableCore onStart={this.onStart}>
  <div>
    <Test>Drag me!</Test>
  </div>
</DraggableCore>

答案 1 :(得分:0)

我在这里玩游戏太晚了,但我希望这对某人有所帮助。你必须给你的组件一个休息道具。您需要这样做,因为 DraggableCore 复制组件并在组件上放置多个事件侦听器。查看 DraggableCore 的渲染。 https://github.com/react-grid-layout/react-draggable/blob/master/lib/DraggableCore.js。您的组件需要能够接收这些事件侦听器。

const Test = ({ children, ...rest }) => {
  return (
    <div {...rest}>{children}</div>
  )
}

const Hello = () => {
  const handleStart = () => console.log('here');

  return (
    <DraggableCore
      onStart={handleStart}
    >
      <Test>Drag me!</Test>
    </DraggableCore>
  );
}