[英]Property 'onClick' is missing in type '{ rating: any; }' but required in type 'RatingType'
I have a simple rating component in reactjs with typescript as follows我在 reactjs 和 typescript 中有一个简单的评级组件,如下所示
Rating.js 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;
I would like to use this rating component in another component but without the onClick function like this below我想在另一个组件中使用此评级组件,但没有 onClick function 如下所示
import Rating from "./Rating";
function Demo() {
return (
//logic goes here
<Rating rating={item.ratings} />
)
}
export default Demo
But I get the following error但我收到以下错误
Property 'onClick' is missing in type '{ rating: any; }' but required in type 'RatingType'.
How can I make the onClick function option when defining the type RatingType?在定义类型 RatingType 时,如何制作 onClick function 选项?
If you don't want onClick
to be required, just make it optional like this:如果您不希望
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;
To make onClick
optional just change RatingType
to:要使
onClick
可选,只需将RatingType
更改为:
export type RatingType = {
rating: number,
onClick?: (x: number) => void, // NOTE the ? to make property optional
style?: React.CSSProperties,
prod?: any
}
Note the ?
注意
?
after the onClick
onClick
后
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.