簡體   English   中英

將擴展的反應組件 class 轉換為與 typescript 一起使用

[英]Converting an extended react component class to work with typescript

我目前正在嘗試將項目從 React 轉換為 typescript。

所以我目前有一個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 組件。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM