簡體   English   中英

React 和 typescript 動態網格調整大小

[英]React and typescript dynamic grid resize

我正在嘗試通過使用 onClick 動作和 typescript 代碼更改 lgEditorSize 值來調整動態網格大小。

聲明初始 lgEditorSize 值

const x: any = {};
x.lgEditorSize=6;

更改 lgEditorSize 值

<Box display='flex' justifyContent='right'>
      <span>Show or hide the sidebar using</span>
      <Button onClick={() => {x.lgEditorSize=12;}}> <ArrowBackIosIcon/> </Button>
      <Button onClick={() => {x.lgEditorSize=6;}}> <ArrowForwardIosIcon/> </Button>  
      <span>Button</span> 
</Box>


<GridContainer>
            <Grid item lg={x.lgEditorSize}>
                Contents
            </Grid>
<GridContainer>      

值已更改但網格未調整大小,任何使用按鈕操作調整網格大小的想法。

您正在更改變量,但組件沒有重新渲染,因為它不知道需要重新渲染。 要實現重新渲染,您需要使用 state,因為 React 足夠聰明,知道當 state 發生變化時,所有使用該 state 的組件都應該重新渲染。

您應該將lgEditorSize放入 state 並使用 state 變量。 它看起來像這樣。

const [lgEditorSize, setLgEditorSize] = useState<GridSize>(6); 

<Box display='flex' justifyContent='right'>
      <span>Show or hide the sidebar using</span>
      <Button onClick={() => setLgEditorSize(12)}> <ArrowBackIosIcon/> </Button>
      <Button onClick={() => setLgEditorSize(6)}> <ArrowForwardIosIcon/> </Button>  
      <span>Button</span> 
</Box>


<GridContainer>
            <Grid item lg={lgEditorSize}>
                Contents
            </Grid>
<GridContainer>  

您可以在此處閱讀有關state和 React 組件生命周期的更多信息: https://reactjs.org/docs/state-and-lifecycle.html

暫無
暫無

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

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