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);
  • 相关阅读:
    冲刺第二阶段第五天
    找水王2
    冲刺第二阶段第四天
    梦断代码阅读笔记03
    冲刺第二阶段第三天
    冲刺第二阶段第二天
    冲刺第二阶段第一天
    梦断代码阅读笔记02
    第十二周学习进度条
    找水王
  • 原文地址:https://www.cnblogs.com/Answer1215/p/10610697.html
Copyright © 2011-2022 走看看