How to toggle boolean state of react component?

前端 未结 9 1918
别跟我提以往
别跟我提以往 2021-01-29 23:45

I\'d like to know how to toggle a boolean state of a react component. For instance:

I have boolean state check in the constructor of my component:

const         


        
9条回答
  •  忘掉有多难
    2021-01-30 00:34

    You could also use React's useState hook to declare local state for a function component. The initial state of the variable toggled has been passed as an argument to the method .useState.

    import { render } from 'react-dom';
    import React from "react";
    
    type Props = {
      text: string,
      onClick(event: React.MouseEvent): void,
    };
    
    export function HelloWorldButton(props: Props) {
      const [toggled, setToggled] = React.useState(false); // returns a stateful value, and a function to update it
      return ;
    }
    
    
    render( console.log('clicked!')} />, document.getElementById('root'));
    

    https://stackblitz.com/edit/react-ts-qga3vc

提交回复
热议问题