zoukankan      html  css  js  c++  java
  • [React] Write a stateful Component with the React useState Hook and TypeScript

    Here we refactor a React TypeScript class component to a function component with a useState hook and discuss how props and state types can be modeled accordingly.

    import * as React from "react";
    import { render } from "react-dom";
    
    import "./styles.css";
    
    type ButtonProps = {
      label?: string;
      children: React.ReactNode;
    };
    type ButtonState = {
      isOn: boolean;
    };
    function Button (props: ButtonProps) {
    
      const [state, setState] = React.useState<ButtonState>({
        isOn: false
      });
    
      const toggle = () => setState({ isOn: !state.isOn });
    
      const { children } = props;
      const { isOn } = state;
      const style = {
        backgroundColor: isOn ? "red" : "green"
      };
      return (
          <button style={style} onClick={toggle}>
            {children(isOn)}
          </button>
        );
    }
    
    Button.defaultProps = {
      label: "Hello World!"
    };
    
    function App() {
      return (
        <Button>
          {isOn => (isOn ? <div> Turn off</div> : <div> Turn on</div>)}
        </Button>
      );
    }
    
    const rootElement = document.getElementById("root");
    render(<App />, rootElement);
  • 相关阅读:
    SQLite的sqlite_sequence表
    缓存区溢出漏洞工具Doona
    SQLite的sqlite_master表
    dfs1321
    三维bfs(HUD1253胜利大逃亡)
    dfs模版
    poj3259: Wormholes(BF模板题)
    Bellman-Ford算法
    POJ1611:The Suspects(模板题)
    poj3126
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10610697.html
Copyright © 2011-2022 走看看