ResizableBox.tsx 2.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112
  1. import React, { SyntheticEvent } from 'react'
  2. import Resizable from './Resizable'
  3. import { ResizableProps, ResizeCallbackData } from './types'
  4. type ResizableBoxState = {
  5. width: number
  6. height: number
  7. propsWidth: number
  8. propsHeight: number
  9. }
  10. // An example use of Resizable.
  11. export default class ResizableBox extends React.Component<
  12. ResizableProps,
  13. ResizableBoxState
  14. > {
  15. public static defaultProps: Partial<ResizableProps> = {
  16. handleSize: [20, 20]
  17. }
  18. public state: Readonly<ResizableBoxState> = {
  19. width: this.props.width,
  20. height: this.props.height,
  21. propsWidth: this.props.width,
  22. propsHeight: this.props.height
  23. }
  24. static getDerivedStateFromProps(
  25. props: ResizableProps,
  26. state: ResizableBoxState
  27. ) {
  28. // If parent changes height/width, set that in our state.
  29. if (
  30. state.propsWidth !== props.width ||
  31. state.propsHeight !== props.height
  32. ) {
  33. return {
  34. width: props.width,
  35. height: props.height,
  36. propsWidth: props.width,
  37. propsHeight: props.height
  38. }
  39. }
  40. return {}
  41. }
  42. private onResize = (e: SyntheticEvent, data: ResizeCallbackData) => {
  43. const { size } = data
  44. if (this.props.onResize) {
  45. if (e.persist) {
  46. e.persist()
  47. }
  48. this.setState(
  49. size,
  50. () => this.props.onResize && this.props.onResize(e, data)
  51. )
  52. } else {
  53. this.setState(size)
  54. }
  55. }
  56. public render() {
  57. // Basic wrapper around a Resizable instance.
  58. // If you use Resizable directly, you are responsible for updating the child component
  59. // with a new width and height.
  60. const {
  61. handle,
  62. handleSize,
  63. onResize,
  64. onResizeStart,
  65. onResizeStop,
  66. draggableOpts,
  67. minConstraints,
  68. maxConstraints,
  69. lockAspectRatio,
  70. axis,
  71. width,
  72. height,
  73. scale,
  74. resizeHandles,
  75. ...props
  76. } = this.props
  77. return (
  78. <Resizable
  79. handle={handle}
  80. handleSize={handleSize}
  81. width={this.state.width}
  82. height={this.state.height}
  83. scale={scale}
  84. onResizeStart={onResizeStart}
  85. onResize={this.onResize}
  86. onResizeStop={onResizeStop}
  87. draggableOpts={draggableOpts}
  88. minConstraints={minConstraints}
  89. maxConstraints={maxConstraints}
  90. lockAspectRatio={lockAspectRatio}
  91. axis={axis}
  92. resizeHandles={resizeHandles}
  93. >
  94. <div
  95. style={{
  96. width: this.state.width + 'px',
  97. height: this.state.height + 'px'
  98. }}
  99. {...props}
  100. />
  101. </Resizable>
  102. )
  103. }
  104. }