简体   繁体   中英

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

I'm new to React and wondering how to change this code so that I'm not using any for the add function that is DI'd into the component.

Most of what I read says to use the React mouse click event type but that has only 1 param and isn't really what is going on anyway so seems bad two different ways.

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;

The correct type would be:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM