反应和打字稿动态网格调整大小

React and typescript dynamic grid resize

我正在尝试通过使用 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>      

值已更改但网格未调整大小,有任何使用按钮操作调整网格大小的想法。

您正在更改变量,但组件没有重新渲染,因为它不知道需要重新渲染。要实现重新渲染,你需要使用状态,因为 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