How to change component size in react
How to change the size of a component in React: 1. Use "React.cloneElement" to enhance the wrapped component; 2. Set absolute positioning on the wrapped component and add four resizable drag bars within the component. ;3. Click the drag bar and drag it to change the size of the DragBox.
#The operating environment of this tutorial: Windows 10 system, react18 version, Dell G3 computer.
How to change component size in react?
Handwriting a React drag-and-drop resizing component
1. Implementation process
1. Use React.cloneElement to enhance the package component, and set the absolute value in the package component Position and add four resizable drag bars within the component. When you click the drag bar and drag it, the size of the DragBox will change, as follows:
2. Use:
<DragBox dragAble={true} minWidth={350} minHeight={184} edgeDistance={[10, 10, 10, 10]} dragCallback={this.dragCallback} > {/* 使用DragBox拖动组件包裹需要调整大小的盒子 */} <div style={{ top: 100 + 'px', left: 100 + 'px', width: 350, height: 184, backgroundColor: "white" }}> <div style={{ backgroundColor: "yellow", width: "100%", height: 30 }}></div> <div style={{ backgroundColor: "green", width: "100%", height: 30 }}></div> <div style={{ backgroundColor: "blue", width: "100%", height: 30 }}></div> </div> </DragBox>
2. Code
DragBox component
import React, { Component, Fragment } from 'react'; import styles from "./DragBox.less"; /** * 拖拽的公共组件 * 接收参数: * dragAble:是否开启拖拽 * minWidth:最小调整宽度 * minHeight:最小调整高度 * edgeDistance:数组,拖拽盒子里浏览器上下左右边缘的距离,如果小于这个距离就不会再进行调整宽高 * dragCallback:拖拽回调 * * 使用: * 在DragBox组件放需要实现拖拽的div,DragBox组件内会设置position:absolute(React.cloneElement) */ class DragBox extends Component { constructor(props) { super(props); // 父组件盒子 this.containerRef = React.createRef(); // 是否开启尺寸修改 this.reSizeAble = false; // 鼠标按下时的坐标,并在修改尺寸时保存上一个鼠标的位置 this.clientX, this.clientY; // 鼠标按下时的位置,使用n、s、w、e表示 this.direction = ""; // 拖拽盒子里浏览器上下左右边缘的距离,如果小于这个距离就不会再进行调整宽高 this.edgeTopDistance = props.edgeDistance[0] || 10; this.edgeBottomDistance = props.edgeDistance[1] || 10; this.edgeLeftDistance = props.edgeDistance[2] || 10; this.edgeRightDistance = props.edgeDistance[3] || 10; } componentDidMount(){ // body监听移动事件 document.body.addEventListener('mousemove', this.move); // 鼠标松开事件 document.body.addEventListener('mouseup', this.up); } /** * 清除调整宽高的监听 */ clearEventListener() { document.body.removeEventListener('mousemove', this.move); document.body.removeEventListener('mouseup', this.up); } componentWillUnmount() { this.clearEventListener(); } /** * 鼠标松开时结束尺寸修改 */ up = () => { this.reSizeAble = false; this.direction = ""; } /** * 鼠标按下时开启尺寸修改 * @param {*} e * @param {String} direction 记录点击上下左右哪个盒子的标识 */ down = (e, direction) => { this.direction = direction; this.reSizeAble = true; this.clientX = e.clientX; this.clientY = e.clientY; } /** * 鼠标按下事件 监听鼠标移动,修改父节dom位置 * @param {DocumentEvent} e 事件参数 * @param {Boolean} changeLeft 是否需要调整left * @param {Boolean} changeTop 是否需要调整top * @param {Number} delta 调整位置的距离差 */ changeLeftAndTop = (event, changeLeft, changeTop, delta) => { let ww = document.documentElement.clientWidth; let wh = window.innerHeight; if (event.clientY < 0 || event.clientX < 0 || event.clientY > wh || event.clientX > ww) { return false; } if (changeLeft) { this.containerRef.current.style.left = Math.max(this.containerRef.current.offsetLeft + delta, this.edgeLeftDistance) + 'px'; } if (changeTop) { this.containerRef.current.style.top = Math.max(this.containerRef.current.offsetTop + delta, this.edgeTopDistance) + 'px'; } } /** * 鼠标移动事件 * @param {*} e */ move = (e) => { // 当开启尺寸修改时,鼠标移动会修改div尺寸 if (this.reSizeAble) { let finalValue; // 鼠标按下的位置在上部,修改高度 if (this.direction === "top") { // 1.距离上边缘10 不修改 // 2.因为按着顶部修改高度会修改top、height,所以需要判断e.clientY是否在offsetTop和this.clientY之间(此时说明处于往上移动且鼠标位置在盒子上边缘之下),不应该移动和调整盒子宽高 if (e.clientY <= this.edgeTopDistance || (this.containerRef.current.offsetTop < e.clientY && e.clientY < this.clientY)){ this.clientY = e.clientY; return; } finalValue = Math.max(this.props.minHeight, this.containerRef.current.offsetHeight + (this.clientY - e.clientY)); // 移动的距离,如果移动的距离不为0需要调整高度和top let delta = this.containerRef.current.offsetHeight - finalValue; if(delta !== 0){ this.changeLeftAndTop(e, false, true, delta); this.containerRef.current.style.height = finalValue + "px"; } this.clientY = e.clientY; } else if (this.direction === "bottom") {// 鼠标按下的位置在底部,修改高度 // 1.距离下边缘10 不修改 // 2.判断e.clientY是否处于往下移动且鼠标位置在盒子下边缘之上,不应该调整盒子宽高 if (window.innerHeight - e.clientY <= this.edgeBottomDistance || (this.containerRef.current.offsetTop + this.containerRef.current.offsetHeight > e.clientY && e.clientY > this.clientY)) { this.clientY = e.clientY; return; } finalValue = Math.max(this.props.minHeight, this.containerRef.current.offsetHeight + (e.clientY - this.clientY)); this.containerRef.current.style.height = finalValue + "px"; this.clientY = e.clientY; } else if (this.direction === "right") { // 鼠标按下的位置在右边,修改宽度 // 1.距离右边缘10 不修改 // 2.判断e.clientY是否处于往右移动且鼠标位置在盒子右边缘之左,不应该调整盒子宽高 if (document.documentElement.clientWidth - e.clientX <= this.edgeRightDistance || (this.containerRef.current.offsetLeft + this.containerRef.current.offsetWidth > e.clientX && e.clientX > this.clientX)) { this.clientX = e.clientX; return; } // 最小为UI设计this.props.minWidth,最大为 改边距离屏幕边缘-10,其他同此 let value = this.containerRef.current.offsetWidth + (e.clientX - this.clientX); finalValue = step(value, this.props.minWidth, document.body.clientWidth - this.edgeRightDistance - this.containerRef.current.offsetLeft); this.containerRef.current.style.width = finalValue + "px"; this.clientX = e.clientX; } else if (this.direction === "left") {// 鼠标按下的位置在左边,修改宽度 // 1.距离左边缘10 不修改 // 2.因为按着顶部修改高度会修改left、height,所以需要判断e.clientY是否在offsetLeft和this.clientY之间(此时说明处于往左移动且鼠标位置在盒子左边缘之左),不应该移动和调整盒子宽高 if (e.clientX <= this.edgeLeftDistance || (this.containerRef.current.offsetLeft < e.clientX && e.clientX < this.clientX)) { this.clientX = e.clientX; return; } let value = this.containerRef.current.offsetWidth + (this.clientX - e.clientX); finalValue = step(value, this.props.minWidth, this.containerRef.current.offsetWidth - this.edgeLeftDistance + this.containerRef.current.offsetLeft); // 移动的距离,如果移动的距离不为0需要调整宽度和left let delta = this.containerRef.current.offsetWidth - finalValue; if(delta !== 0){ // 需要修改位置,直接修改宽度只会向右增加 this.changeLeftAndTop(e, true, false, delta); this.containerRef.current.style.width = finalValue + "px"; } this.clientX = e.clientX; } this.props.dragCallback && this.props.dragCallback(this.direction, finalValue); } } render() { // 四个红色盒子 用于鼠标移动到上面按下进行拖动 const children = ( <Fragment key={"alphaBar"}> <div key={1} className={styles.alphaTopBar} onMouseDown={(e) => this.down(e, "top")}></div> <div key={2} className={styles.alphaBottomBar} onMouseDown={(e) => this.down(e, "bottom")}></div> <div key={3} className={styles.alphaLeftBar} onMouseDown={(e) => this.down(e, "left")}></div> <div key={4} className={styles.alphaRightBar} onMouseDown={(e) => this.down(e, "right")}></div> </Fragment> ); // 给传进来的children进行加强:添加position:"absolute",添加四个用于拖动的透明盒子 const childrenProps = this.props.children.props; const cloneReactElement = React.cloneElement( this.props.children, { style: { // 复用原来的样式 ...childrenProps.style, // 添加position:"absolute" position: "absolute" }, ref: this.containerRef }, // 复用children,添加四个用于拖动的红色盒子 [childrenProps.children, children] ); return ( <Fragment> { cloneReactElement } </Fragment> ); } } /** * 取最大和最小值之间的值 * @param {*} value * @param {*} min * @param {*} max * @returns */ function step(value, min, max) { if (value < min) { return min; } else if (value > max) { return max; } else { return value; } } export default DragBox;
DragBox component drag bar style
.alphaTopBar{ position: absolute; width: 100%; height: 8px; top: -5px; left: 0; background-color: red; cursor: row-resize; } .alphaBottomBar{ position: absolute; width: 100%; height: 8px; bottom: -5px; left: 0; background-color: red; cursor: row-resize; } .alphaLeftBar{ position: absolute; width: 8px; height: 100%; top: 0; left: -5px; background-color: red; cursor: col-resize; } .alphaRightBar{ position: absolute; width: 8px; height: 100%; top: 0; right: -5px; background-color: red; cursor: col-resize; }
Recommended learning: "react video tutorial》
The above is the detailed content of How to change component size in react. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics



React front-end and back-end separation guide: How to achieve front-end and back-end decoupling and independent deployment, specific code examples are required In today's web development environment, front-end and back-end separation has become a trend. By separating front-end and back-end code, development work can be made more flexible, efficient, and facilitate team collaboration. This article will introduce how to use React to achieve front-end and back-end separation, thereby achieving the goals of decoupling and independent deployment. First, we need to understand what front-end and back-end separation is. In the traditional web development model, the front-end and back-end are coupled

How to use React and Flask to build simple and easy-to-use web applications Introduction: With the development of the Internet, the needs of web applications are becoming more and more diverse and complex. In order to meet user requirements for ease of use and performance, it is becoming increasingly important to use modern technology stacks to build network applications. React and Flask are two very popular frameworks for front-end and back-end development, and they work well together to build simple and easy-to-use web applications. This article will detail how to leverage React and Flask

Many users always encounter some problems when playing some games on win10, such as screen freezes and blurred screens. At this time, we can solve the problem by turning on the directplay function, and the operation method of the function is also Very simple. How to install directplay, the old component of win10 1. Enter "Control Panel" in the search box and open it 2. Select large icons as the viewing method 3. Find "Programs and Features" 4. Click on the left to enable or turn off win functions 5. Select the old version here Just check the box

How to build a reliable messaging application with React and RabbitMQ Introduction: Modern applications need to support reliable messaging to achieve features such as real-time updates and data synchronization. React is a popular JavaScript library for building user interfaces, while RabbitMQ is a reliable messaging middleware. This article will introduce how to combine React and RabbitMQ to build a reliable messaging application, and provide specific code examples. RabbitMQ overview:

ReactRouter User Guide: How to Implement Front-End Routing Control With the popularity of single-page applications, front-end routing has become an important part that cannot be ignored. As the most popular routing library in the React ecosystem, ReactRouter provides rich functions and easy-to-use APIs, making the implementation of front-end routing very simple and flexible. This article will introduce how to use ReactRouter and provide some specific code examples. To install ReactRouter first, we need

How to use React and Apache Kafka to build real-time data processing applications Introduction: With the rise of big data and real-time data processing, building real-time data processing applications has become the pursuit of many developers. The combination of React, a popular front-end framework, and Apache Kafka, a high-performance distributed messaging system, can help us build real-time data processing applications. This article will introduce how to use React and Apache Kafka to build real-time data processing applications, and

PHP, Vue and React: How to choose the most suitable front-end framework? With the continuous development of Internet technology, front-end frameworks play a vital role in Web development. PHP, Vue and React are three representative front-end frameworks, each with its own unique characteristics and advantages. When choosing which front-end framework to use, developers need to make an informed decision based on project needs, team skills, and personal preferences. This article will compare the characteristics and uses of the three front-end frameworks PHP, Vue and React.

The default display behavior for components in the Angular framework is not for block-level elements. This design choice promotes encapsulation of component styles and encourages developers to consciously define how each component is displayed. By explicitly setting the CSS property display, the display of Angular components can be fully controlled to achieve the desired layout and responsiveness.
