繁体   English   中英

'{ rating: any; 类型中缺少属性 'onClick' }' 但在“RatingType”类型中是必需的

[英]Property 'onClick' is missing in type '{ rating: any; }' but required in type 'RatingType'

我在 reactjs 和 typescript 中有一个简单的评级组件,如下所示

Rating.js

export type RatingType = {
  rating: number,
  onClick: (x: number) => void
  style?: React.CSSProperties,
  prod?: any
}

const Rating: React.FC <RatingType> = ({ rating, onClick, style }) => {
  return (
    <>
      //do something here
    </>
  );
};

export default Rating;

我想在另一个组件中使用此评级组件,但没有 onClick function 如下所示

import Rating from "./Rating";
function Demo() {
  return (
    //logic goes here
    <Rating rating={item.ratings}  />
  )
}

export default Demo

但我收到以下错误

Property 'onClick' is missing in type '{ rating: any; }' but required in type 'RatingType'.

在定义类型 RatingType 时,如何制作 onClick function 选项?

如果您不希望onClick是必需的,只需将其设为可选,如下所示:

export type RatingType = {
  rating: number,
  onClick?: (x: number) => void // <- Add question mark there
  style?: React.CSSProperties,
  prod?: any
}

const Rating: React.FC <RatingType> = ({ rating, onClick, style }) => {
  return (
    <>
      //do something here
    </>
  );
};

export default Rating;

要使onClick可选,只需将RatingType更改为:

export type RatingType = {
  rating: number,
  onClick?: (x: number) => void, // NOTE the ? to make property optional
  style?: React.CSSProperties,
  prod?: any
}

注意? onClick

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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