首页 > 解决方案 > 使用带有反应钩子的 react-rnd

问题描述

我正在使用react-rnd并希望将它与 hooks 组件一起使用。从文档中的示例中,我不明白如何实现它。使用类组件,我可以复制示例:

<Rnd
  size={{ width: this.state.width,  height: this.state.height }}
  position={{ x: this.state.x, y: this.state.y }}
  onDragStop={(e, d) => { this.setState({ x: d.x, y: d.y }) }}
  onResizeStop={(e, direction, ref, delta, position) => {
    this.setState({
      width: ref.style.width,
      height: ref.style.height,
      ...position,
    });
  }}
>
  001
</Rnd>

我不明白道具中发生...position了什么。onResizeStop

谁能帮助我了解...position正在做什么以及如何将其变成挂钩组件?

标签: reactjs

解决方案


这应该可以工作,或者至少给你一个想法:

const [state, setState] = useState({x:0, y:0, width:0, height:0});

<Rnd
  size={{ width: state.width,  height: state.height }}
  position={{ x: state.x, y: state.y }}
  onDragStop={(e, d) => { setState({...state, x: d.x, y: d.y}) }}
  onResizeStop={(e, direction, ref, delta, position) => {
    setState({
        width: ref.style.width, 
        height: ref.style.height,
        ...position
    })
  }}
>
  001
</Rnd>

您可以将零件替换为...position

setState({
    width: ref.style.width, 
    height: ref.style.height,
    x: position.x,
    y: position.y 
});

一样的 :)


推荐阅读