React封装组件怎么获取子组件属性?

主要是想实现一个简单拖拽布局的功能,代码如下:

import React from 'react';
import classNames from "classnames/bind";
import styles from './index.less'

const cx = classNames.bind(styles);
export class Box extends React.PureComponent{

  componentDidMount() {
    const resize = document.getElementById('drag_resize');
    const handle = document.getElementById('drag_handle');
    const left = document.getElementById('drag_aside');
    const right = document.getElementById('drag_main');
    const box = this.boxRef;
    handle.onmousedown = function (e) {
      const startX = e.clientX;
      resize.left = resize.offsetLeft;
      document.onmousemove = function (e) {
        const endX = e.clientX;

        let moveLen = resize.left + (endX - startX);
        const maxT = box.clientWidth - resize.offsetWidth;
        if (moveLen < 150) moveLen = 150;
        if (moveLen > maxT - 150) moveLen = maxT - 150;

        resize.style.left = moveLen;
        left.style.width = moveLen + "px";
        right.style.width = (box.clientWidth - moveLen - 1) + "px";
      };
      document.onmouseup = function (evt) {
        document.onmousemove = null;
        document.onmouseup = null;
        resize.releaseCapture && resize.releaseCapture();
      };
      resize.setCapture && resize.setCapture();
      return false;
    }
  }

  render() {
    const { children, style } = this.props;
    const mergeClass = cx ({
      box: true,
      'slide-container': true
    });
    return (
      <div ref={ref=>{ this.boxRef = ref }} className={mergeClass}>
        {children}
      </div>
    )
  }
}

export class Resize extends React.PureComponent{

  render() {
    return (
      <div id='drag_resize' className={styles.resize}>
        <div id='drag_handle' className={styles.handle} />
      </div>
    )
  }
}

export class Left extends React.PureComponent{

  render() {
    const { children, style } = this.props;
    const mergeClass = cx ({
      left: true,
      container__sidebar: true,
      'custom-scroll-wrapper': true
    });
    return (
      <aside id='drag_aside' className={mergeClass} style={style}>
        {children}
      </aside>
    )
  }
}

export class Right extends React.PureComponent{

  render() {
    const { children, style } = this.props;
    const mergeClass = cx ({
      right: true,
      container__main: true
    });
    return (
      <main id='drag_main' className={mergeClass} style={style}>
        {children}
      </main>
    )
  }
}

我想这样使用:

import { Box, Left, Right, Resize } from "@/components/DragLayout";
// render
<Box>
    <Left>
        ...sth
    </Left>
    <Right>
        ...sth
    </Right>
</Box>

现在不知道怎么去取下边组件的值,所以用id去取了,但是id是可能冲突的,
有没什么比较优雅的方法封装这组件

阅读 1.8k
2 个回答

函数组件可以用 useImperativeHandle, forwardRef 配合做到 class 不太清楚了 很久没写class 组件了

react的思路不推荐你去这么做,要么就变量提升,要么就context。父组件关心子组件的属性,那就应该变成父组件的属性,然后分配给子组件

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题
宣传栏