TypeScript React Hooks升级路径

时间:2019-06-12 11:20:32

标签: reactjs typescript

我有一个带有一些怪癖的TypeScript组件,我很想将它们转换为功能组件并利用新的React钩子。

我使用符号具有私有功能,

构造函数和默认道具,

还有一个简单的渲染功能。

interface IProps {
  initialCount?: number;
}

interface IState {
  count: number;
}

const increment = Symbol();

class Counter extends React.Component {
  constructor(props)
    super(props);
    this.state = {
      count: props.initialCount!
    };
    this[increment] = this[increment].bind(this);
  }

  public static defaultProps = {
    initialCount: 0
  };

  [increment] = () => {
    const { count } = this.state;
    this.setState({ count: count + 1 });
  };
  render() {
    const { count } = this.state;
    return( <>
      <p>I've been clicked {count} times!</p>
      <button
        onClick={this[increment]}>
        Click me
      </button>
    </>
  }
}

1 个答案:

答案 0 :(得分:0)

一些小技巧:

默认道具更容易,您可以删除!

const Counter = ({ initialCount = 0 }: IProps) => //

我们可以添加useStateuseEffect来管理您的状态。

const Counter = () => {
  const [count, setCount] = React.useState(0);
  React.useEffect(() => {
    document.title = `You clicked ${count} times`;
  });
}

您的函数使用闭包进行了私有化,无需弄乱符号!

const Counter () => {
  const increment = () => setCount(count + 1); 
  return (<div/>)
}

将所有内容放在一起,我们得到:

import Button from "@material-ui/core/Button";
import Typography from "@material-ui/core/Typography";
import * as React from "react";
import "./style.css";

interface IProps {
  initialCount?: number;
}

const style: any = { backgroundColor: "blue" };

const Counter = ({ initialCount = 0 }: IProps) => {
  const [count, setCount] = React.useState(initialCount);
  React.useEffect(() => {
    document.title = `You clicked ${count} times`;
  });

  const increment = () => setCount(count + 1);

  return (
    <div className="byop-app__counter" style={style}>
      <Typography variant="h3">
        You clicked{" "}
        <span data-testid="byop-app__counter-count-value">{count}</span> times
      </Typography>

      <Button
        className="byop-app__counter-button"
        data-testid="byop-app__counter-button"
        variant="contained"
        color="primary"
        onClick={increment}>
        Click me
      </Button>
    </div>
  );
};

export default Counter;