我正在嘗試通過使用 onClick 操作對反應和打字稿代碼更改 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>
值已更改但網格未調整大小,任何使用按鈕操作調整網格大小的想法。
uj5u.com熱心網友回復:
您正在更改變數,但組件不會重新渲染,因為它不知道需要這樣做。為了實作重新渲染,你需要使用狀態,因為 React 足夠聰明,知道當一個狀態改變時,所有使用該狀態的組件都應該重新渲染。
您應該將lgEditorSize放入一個狀態并使用狀態變數。它看起來像這樣。
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
轉載請註明出處,本文鏈接:https://www.uj5u.com/shujuku/392701.html
標籤:javascript css 反应 打字稿 bootstrap-4
