簡體   English   中英

Typescript/React 功能組件的道具 function - 什么類型?

[英]Typescript/React functional component's props function - what type?

我是 React 的新手,想知道如何更改此代碼,以便我不使用任何代碼添加到組件中的添加 function

我讀到的大部分內容都說要使用 React 鼠標單擊事件類型,但它只有 1 個參數,而且無論如何都不是真正發生的事情,所以兩種不同的方式看起來都很糟糕。

import React, { useState } from 'react';

interface IProps {
  count?: number;
  incrementBy?: number;
  onClick: any;
  // EDIT - FIX - correct fn type
  //              I also took optional ? off types in app
  //onClick: (count: number, incrementBy: number) => void;
}

const Description2: React.FC<IProps> = (props: IProps) => (
    <div>
    <p>My favorite number is {props.count}, incrementBying by {props.incrementBy}</p>
    <button 
        onClick={() => props.onClick(props.count, props.incrementBy)}
    >
        Increase
    </button>
  </div>
);

const App: React.FC = () => {

  //initialize state
  const increase = 4;
  const [count, setCount] = useState(increase);
  const [user, setUser] = useState("world");

  const add = (currentCount: number, bump: number) => {
    setCount(currentCount + bump);
  };

  return (
    <div >
          <Description2
          count={count}
          incrementBy={increase} 
          onClick={add} />
    </div>
  );
}

export default App;

正確的類型是:

  (count: number, incrementBy: number) => any

暫無
暫無

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

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