I want to change the state with React common processing.

Asked 2 years ago, Updated 2 years ago, 36 views

There is a switch that switches on and off, and the changeState function is called when switching.
The contents of the key passed as an argument are passed in the form {numberState:true}.
I want to change the state according to the value given, but it doesn't work.
Please let me know if anyone understands.Thank you for your cooperation.

The component uses materialUI

interfaceIstate{
  numbers —boolean;
  symbol:boolean;
  texxt —boolean;
}

const index —FC=()=>{
  const [state, setState] = useState<ISstate>();

 constchangeState=(key:ISstate)=>{
    console.log(key)
    // Unable to change state successfully in setState
    setState({...state,...{key:!key}});
  };

 <Switch
  checked = {numberState}
  onChange={(e)=>changeState({numberState:e.target.checked})}
 />
 <Switch
  checked = {textState}
  onChange={(e)=>changeState({textState:e.target.checked})}
 />
 <Switch
  checked = {symbolState}
  onChange={(e)=>changeState({symbolState:e.target.checked})}
 />

javascript reactjs typescript

2022-09-29 22:55

1 Answers

The value obtained in onChange has already been reflected, so I don't think it's necessary to reverse the boolean value.

import React, {FC, useState} from "react";
import {Switch} from "@material-ui/core";

interfaceIState {
  numberState —boolean;
  symbolState:boolean;
  textState:boolean;
}

const initIState = {
  numberState: false,
  symbolState: false,
  textState:false,
};

const Index: FC=()=>{
  const [state, setState] = useState<ISstate> (initState);

  constchangeState=(key:Partial<ISstate>)=>{
    console.log(key);
    setState({...state,...key});
  };

  return(
    <>
      <Switch
        checked = {state.numberState}
        onChange={(e)=>changeState({numberState:e.target.checked})}
      />
      <Switch
        checked = {state.textState}
        onChange={(e)=>changeState({textState:e.target.checked})}
      />
      <Switch
        checked = {state.symbolState}
        onChange={(e)=>changeState({symbolState:e.target.checked})}
      />
    </>
  );
};
export default Index;


2022-09-29 22:55

If you have any answers or tips


© 2024 OneMinuteCode. All rights reserved.