[英]Converting an extended react component class to work with typescript
I am currently attempting to convert a project from react to typescript.我目前正在尝试将项目从 React 转换为 typescript。
So I currently have a jsx file I want to convert to tsx and the code is the following所以我目前有一个jsx文件我想转换成tsx,代码如下
class Button extends React.Component {
onClickCallback = e => {
if(this.props.onClick){
this.props.onClick(e);
}
}
}
I am wondering what the first steps would be, I need to create the props right?我想知道第一步是什么,我需要制作道具吗?
props = {onClick: } // But what would it be? {}?
Thanks谢谢
glad you are adapting Typescript in your project:)很高兴您在项目中调整 Typescript :)
When using Typescript in React you would do something like below:在 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} />
)
}
Hope this clarifies how to type React component with Typescript.希望这能阐明如何使用 Typescript 键入 React 组件。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.