[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);

猜你喜欢

转载自www.cnblogs.com/Answer1215/p/10610697.html
今日推荐