반응에서 구성 요소 크기를 변경하는 방법
React에서 구성 요소의 크기를 변경하는 방법: 1. "React.cloneElement"를 사용하여 래핑된 구성 요소를 향상합니다. 2. 래핑된 구성 요소에 절대 위치를 설정하고 구성 요소 내에 크기 조정 가능한 드래그 바 4개를 추가합니다. 바와 드래그는 DragBox의 크기를 변경합니다.
이 튜토리얼의 운영 환경: Windows 10 시스템, React18 버전, Dell G3 컴퓨터.
반응에서 구성 요소 크기를 변경하는 방법은 무엇입니까?
React 드래그 앤 드롭 크기 조정 가능한 구성 요소 필기
1. 구현 프로세스
1. React.cloneElement를 사용하여 래핑된 구성 요소를 강화하고, 래핑된 구성 요소에 절대 위치를 설정하고, 구성 요소에 4개의 크기 조정 가능한 요소를 추가합니다. 바, 드래그 바를 클릭하고 드래그하면 DragBox의 크기가 다음과 같이 변경됩니다.
2. 사용:
<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. 코드
DragBox 컴포넌트
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 컴포넌트 드래그 바 스타일
.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; }
추천 학습: "react 비디오 튜토리얼"
위 내용은 반응에서 구성 요소 크기를 변경하는 방법의 상세 내용입니다. 자세한 내용은 PHP 중국어 웹사이트의 기타 관련 기사를 참조하세요!

핫 AI 도구

Undresser.AI Undress
사실적인 누드 사진을 만들기 위한 AI 기반 앱

AI Clothes Remover
사진에서 옷을 제거하는 온라인 AI 도구입니다.

Undress AI Tool
무료로 이미지를 벗다

Clothoff.io
AI 옷 제거제

AI Hentai Generator
AI Hentai를 무료로 생성하십시오.

인기 기사

뜨거운 도구

메모장++7.3.1
사용하기 쉬운 무료 코드 편집기

SublimeText3 중국어 버전
중국어 버전, 사용하기 매우 쉽습니다.

스튜디오 13.0.1 보내기
강력한 PHP 통합 개발 환경

드림위버 CS6
시각적 웹 개발 도구

SublimeText3 Mac 버전
신 수준의 코드 편집 소프트웨어(SublimeText3)

뜨거운 주제











React와 WebSocket을 사용하여 실시간 채팅 애플리케이션을 구축하는 방법 소개: 인터넷의 급속한 발전과 함께 실시간 커뮤니케이션이 점점 더 주목을 받고 있습니다. 실시간 채팅 앱은 현대 사회 생활과 직장 생활에서 필수적인 부분이 되었습니다. 이 글에서는 React와 WebSocket을 사용하여 간단한 실시간 채팅 애플리케이션을 구축하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. 1. 기술적 준비 실시간 채팅 애플리케이션 구축을 시작하기 전에 다음과 같은 기술과 도구를 준비해야 합니다. React: 구축을 위한 것

React 프론트엔드와 백엔드 분리 가이드: 프론트엔드와 백엔드 분리 및 독립적 배포를 달성하는 방법, 구체적인 코드 예제가 필요합니다. 오늘날의 웹 개발 환경에서는 프론트엔드와 백엔드 분리가 추세가 되었습니다. . 프런트엔드 코드와 백엔드 코드를 분리함으로써 개발 작업을 보다 유연하고 효율적으로 수행하고 팀 협업을 촉진할 수 있습니다. 이 기사에서는 React를 사용하여 프런트엔드와 백엔드 분리를 달성하고 이를 통해 디커플링 및 독립적 배포 목표를 달성하는 방법을 소개합니다. 먼저 프론트엔드와 백엔드 분리가 무엇인지 이해해야 합니다. 전통적인 웹 개발 모델에서는 프런트엔드와 백엔드가 결합되어 있습니다.

React와 Flask를 사용하여 간단하고 사용하기 쉬운 웹 애플리케이션을 구축하는 방법 소개: 인터넷의 발전과 함께 웹 애플리케이션의 요구 사항은 점점 더 다양해지고 복잡해지고 있습니다. 사용 편의성과 성능에 대한 사용자 요구 사항을 충족하기 위해 최신 기술 스택을 사용하여 네트워크 애플리케이션을 구축하는 것이 점점 더 중요해지고 있습니다. React와 Flask는 프런트엔드 및 백엔드 개발을 위한 매우 인기 있는 프레임워크이며, 함께 잘 작동하여 간단하고 사용하기 쉬운 웹 애플리케이션을 구축합니다. 이 글에서는 React와 Flask를 활용하는 방법을 자세히 설명합니다.

많은 사용자가 win10에서 일부 게임을 플레이할 때 화면이 멈추거나 화면이 흐려지는 등의 문제에 항상 직면합니다. 이때 다이렉트 플레이 기능을 켜면 문제를 해결할 수 있으며 기능 작동 방법도 매우 간단합니다. 이전 버전의 win10 컴포넌트 다이렉트플레이 설치 방법 1. 검색 상자에 "제어판"을 입력하고 엽니다. 2. 보기 방법으로 큰 아이콘을 선택합니다. 3. "프로그램 및 기능"을 찾습니다. 4. 활성화 또는 활성화하려면 왼쪽을 클릭합니다. Win 기능 끄기 5. 여기에서 이전 버전을 선택하세요. 확인란을 선택하세요.

React 및 RabbitMQ를 사용하여 안정적인 메시징 애플리케이션을 구축하는 방법 소개: 최신 애플리케이션은 실시간 업데이트 및 데이터 동기화와 같은 기능을 달성하기 위해 안정적인 메시징을 지원해야 합니다. React는 사용자 인터페이스 구축을 위한 인기 있는 JavaScript 라이브러리인 반면 RabbitMQ는 안정적인 메시징 미들웨어입니다. 이 기사에서는 React와 RabbitMQ를 결합하여 안정적인 메시징 애플리케이션을 구축하는 방법을 소개하고 구체적인 코드 예제를 제공합니다. RabbitMQ 개요:

ReactRouter 사용자 가이드: 프런트엔드 라우팅 제어 구현 방법 단일 페이지 애플리케이션의 인기로 인해 프런트엔드 라우팅은 무시할 수 없는 중요한 부분이 되었습니다. React 생태계에서 가장 널리 사용되는 라우팅 라이브러리인 ReactRouter는 풍부한 기능과 사용하기 쉬운 API를 제공하여 프런트 엔드 라우팅 구현을 매우 간단하고 유연하게 만듭니다. 이 기사에서는 ReactRouter를 사용하는 방법을 소개하고 몇 가지 구체적인 코드 예제를 제공합니다. ReactRouter를 먼저 설치하려면 다음이 필요합니다.

React 및 Apache Kafka를 사용하여 실시간 데이터 처리 애플리케이션을 구축하는 방법 소개: 빅 데이터 및 실시간 데이터 처리가 증가함에 따라 실시간 데이터 처리 애플리케이션 구축은 많은 개발자의 추구 사항이 되었습니다. 널리 사용되는 프런트엔드 프레임워크인 React와 고성능 분산 메시징 시스템인 Apache Kafka의 조합은 실시간 데이터 처리 애플리케이션을 구축하는 데 도움이 될 수 있습니다. 이 기사에서는 React와 Apache Kafka를 사용하여 실시간 데이터 처리 애플리케이션을 구축하는 방법을 소개합니다.

Angular 프레임워크의 구성 요소에 대한 기본 표시 동작은 블록 수준 요소에 대한 것이 아닙니다. 이 디자인 선택은 구성 요소 스타일의 캡슐화를 촉진하고 개발자가 각 구성 요소가 표시되는 방법을 의식적으로 정의하도록 장려합니다. CSS 속성 표시를 명시적으로 설정하면 Angular 구성 요소의 표시를 완전히 제어하여 원하는 레이아웃과 응답성을 얻을 수 있습니다.
