打字稿/反应功能组件的道具功能-什么类型?

时间:2019-11-08 23:44:47

标签: javascript reactjs typescript functional-programming components

我是React的新手,想知道如何更改此代码,以便不对添加到组件中的添加函数使用 any

我读到的大部分内容都说使用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;

1 个答案:

答案 0 :(得分:1)

正确的类型是:

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