У меня есть компонент 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>
</>
}
}





Несколько небольших советов:
Использовать реквизит по умолчанию намного проще, вы можете отказаться от него !
const Counter = ({ initialCount = 0 }: IProps) => //
Мы можем добавить useState и useEffect для управления вашим состоянием.
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;