简体   繁体   中英

React and typescript dynamic grid resize

I'm trying to make dynamic grid resize by change lgEditorSize value using onClick action for react and typescript code.

Declare initial lgEditorSize value

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

Change lgEditorSize value

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

The value is changed but grid not resized,Any thoughts to resize Grid using Button action.

You are changing the variable, but the Component isn't re-rendering because it doesn't know it needs to. To achieve re-renders, you need to use state, because React is smart enough to know that when a state changes, all the components using that state should re-render.

You should place the lgEditorSize into a state and use the state variable. It would look something like this.

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>  

You can read more about state and the React component lifecycle here: https://reactjs.org/docs/state-and-lifecycle.html

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM