簡體   English   中英

反應等待另一個組件完成渲染

[英]react wait for another component to finish rendering

我有以下情況:2個組件A和B。A在頁面布局中在B之上。 我希望使用它的top動態地計算B height css規則。 B的top受到A的影響,因為A呈現在其上方。 我給B附加了一個引用,然后通過計算ref的邊界rect並從top計算所需的height來應用它的樣式。
當組件A比組件B花費更多的時間來完全渲染時會出現問題,因為A加載的圖像要花更多的時間來加載,使得B的頂部在已經渲染之后才能移位a,因此函數中height的計算需要在A完全渲染之后以某種方式再次被調用,但是我不想僅僅因為B在A之前渲染而將B耦合到A,我該怎么辦才能解決這個問題?

您可以使用CSS Flexbox解決此問題,請檢查下面的代碼段。

 (function () { var loadImgBtn = document.getElementById('load-image-btn'); var loadedImg = document.getElementById('loaded-image'); loadImgBtn.addEventListener('click', function () { loadedImg.style.display = 'block'; }); })(); 
 .flexbox { display: flex; flex-direction: column; align-items: stretch; min-height: 350px; } #loaded-image { display: none; } #first-block { background: green; } #second-block { background: red; flex-grow: 1; } 
 <div class="flexbox"> <div id="first-block"> Component A <img id="loaded-image" src="https://images.pexels.com/photos/248797/pexels-photo-248797.jpeg?auto=compress&cs=tinysrgb&dpr=1&w=500"> </div> <div id="second-block">Component B</div> </div> <button id="load-image-btn">Load Image</button> 

如果要以編程方式計算它,則可以使用refforwardRef,如果您需要將ref進一步傳遞給類似這樣的東西

const ComponentA = React.forwardRef((props, ref) => (
  <div ref={ref} className="componentA">
    {props.children}
  </div>
));

const ComponentB = React.forwardRef((props, ref) => (
  <div ref={ref} className="componentB">
    {props.children}
  </div>
));

class App extends React.Component{

  constructor(props){
    super(props);
    this.refA = React.createRef();
    this.refB = React.createRef();

  }

  componentDidMount(){
    console.log(this.refA.current.clientHeight,this.refB.current.clientHeight);
  }
  render(){

    return (
      <div className="App">
        <ComponentA calculatedHeight={componentAHeight} ref={this.refA} >Component A</ComponentA>
        <ComponentB calculatedHeight={componentBHeight} ref={this.refB} >Component B</ComponentB>
      </div>
    );
  }

}

您也可以使用findDOMNode來執行此操作(在嚴格模式下不推薦使用)。 react-sizeme也可能有幫助。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM