转换扩展的反应组件类以使用打字稿



我目前正在尝试将项目从反应转换为打字稿。

所以我目前有一个 jsx 文件,我想转换为 tsx,代码如下

class Button extends React.Component {

onClickCallback = e => {
if(this.props.onClick){
this.props.onClick(e);
}
}
}  

我想知道第一步是什么,我需要创建道具对吗?

props = {onClick: } // But what would it be? {}?

谢谢

很高兴您在项目中改编了Typescript:)

在 React 中使用 Typescript 时,你会做如下的事情:

type ButtonProps = {
// Function props is typed as (arg: ArgumentType) => ReturnType.
// `event` is the argument type for the function.
// `void` is the return type of the function.
onClick?: (event: React.MouseEvent<HTMLButtonElement, MouseEvent>) => void
}
// Class component.
class Button extends React.Component<ButtonProps> {
render() {
return (
<button onClick={this.props.onClick} />
)
}
}
// Function component.
const Button: React.FC<ButtonProps> = ({ onClick }) => {
return (
<button onClick={onClick} />
)
}

希望这能阐明如何使用 Typescript 键入 React 组件。

最新更新