DAWM

Regresar

React - Hooks: useState I

react banner

El Hook de useState ofrece una variable de estado para mantener los datos entre renderizados y una función que coloca el estado para actualizar la variable y provocar que React renderice el componente nuevamente.

Fuente: Managing component state with the useState Hook

Hooks: useState


import * as React from 'react';

...
...

export default function Calculator() {

  {/* Hooks: useState */}
  const [planId, setPlanId] = React.useState(-1);
  const [timeId, setTimeId] = React.useState(-1);

  ...

}
...
	{/* Manejadores de eventos */}
	  
	const handleChangeSelect = (event: SelectChangeEvent) => {
		let newMenuId = parseInt(event.target.value)    
		setPlanId(newMenuId)
	};

	const handleChangeRadio = (event: React.ChangeEvent<HTMLInputElement>) => {
		let newChangeId = parseInt((event.target as HTMLInputElement).value)
		setTimeId(newChangeId)
	};

      {/* JSX */ }

  	return ( ... )
...
...
	{/* Select */}

	...
	</Select>

	<p>
      	{(planId != -1)?menuItems[planId].intro:''}
     </p>
...

y

...
	{/* Radio Group */}

	...
    </RadioGroup>

    <p>
      {(timeId != -1)?radioItems[timeId].description:''}
    </p>
...

react_componentes_useState1

Referencias