react Draggable bounds属性 不超过父级标签
时间: 2024-05-01 08:20:56 浏览: 13
`react-draggable` 的 `bounds` 属性可以设置拖动的范围,以限制组件的移动。如果你要设置拖动元素不超出父级元素的范围,可以将 `bounds` 属性设置为父元素的坐标和宽高。具体做法如下:
```jsx
import Draggable from 'react-draggable';
function MyComponent() {
return (
<div style={{ position: 'relative', width: '300px', height: '300px', border: '1px solid black' }}>
<Draggable bounds="parent">
<div style={{ width: '50px', height: '50px', backgroundColor: 'red' }}>Drag me</div>
</Draggable>
</div>
);
}
```
在这个例子中,`<Draggable>` 组件的 `bounds` 属性设置为 `"parent"`,表示组件只能在父元素内移动。由于父元素已经设置了 `position: relative`,所以 `bounds` 属性会自动计算父元素的坐标和宽高。
注意,如果父元素的 `position` 属性不是 `relative`、`absolute` 或 `fixed`,则需要手动设置父元素的坐标和宽高。例如,如果父元素的 `display` 属性为 `inline-block`,那么需要设置父元素的 `position: relative` 和 `display: block`,才能让 `bounds` 属性生效。
相关推荐
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![zip](https://img-home.csdnimg.cn/images/20210720083736.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)