繁体   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