繁体   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