首页 > 解决方案 > 如何在 React 中的窗口调整大小事件中设置 div 父节点以更改其宽度?

问题描述

该组件正在使用 jQuery 来获取正在工作的元素宽度。这是一个关于设置包装器 div 元素的问题,它的尺寸会随着窗口的大小而变化。目前它始终是 600 像素 x 300 像素。

当父容器达到一定大小时,我正在尝试更改 SVG React 组件的状态。容器是一个名为 withResizeHandler 的 React HOC,包装器节点是一个 div 元素。div 大小使用 jquery 从 resize 事件触发的回调 updateSize 检查。我更改了浏览器窗口大小并执行进入回调,但控制台日志表明该 div 从未改变其原始尺寸 600 像素 x 300 像素。代码在代码笔https://codepen.io/pboulos/pen/rrLYKE?editors=0111上。

const withResizeHandler = (WrappedComponent) => {
  return class extends React.Component {
    state = {
    width: 0,
    height: 0
  }
  //Init 
  componentWillMount(){
    console.log('HOC Resize Props',this.props);
    window.addEventListener("resize", this.updateSize.bind(this));
    this.setState({width:this.props.width, height:this.props.height});
  }

  componentDidMount() {
    this.updateSize();
  }

  componentWillUnmount(){
    $(window).off('resize');
  }

  updateSize = () => {
   // DOM node is the wrapper div element
   var node = ReactDOM.findDOMNode(this);
   const nodeWidth = $(node).width();
   const nodeHeight = $(node).height();
   console.log("Parent Width "+ nodeWidth+" Height "+nodeHeight);

   if (nodeWidth < this.props.width){
    this.setState({width: nodeWidth-20});
   }else{
     this.setState({width: this.props.width});
   } 
 }
 render () {
   return (
     <div style={{"height" : "300px"}}>
       {/* pass down the props from the hoc wrapper */}
       <WrappedComponent width={this.state.width} height={this.state.height}/>
    </div>
   );
  }
 }
}

标签: javascriptjquerycssreactjs

解决方案


一个纯粹的 CSS 解决方案是在 SVG 组件上方和 App flex 根下方的 DOM 层次结构中的所有 div 节点上使用 inline-size(它仍然是实验性的)。对于反应样式示例:

<App>
  <div style={{"inlineSize":"75%"}}>
   <h3> Some Heading </h3>
    <div style={{"inlineSize":"75%"}}>
      <some SVG component>... </SVG>
    </div>
  <div>
</App>

推荐阅读