The react & TS component passes in optional functions and undefined problem handling

TA_ WORLD 2022-06-23 15:54:33 阅读数:926


React&Ts Component passes in optional functions ,undefined Problem handling

Components props The type definition

interface PinProps extends React.ComponentProps<typeof Rate> {

onCheckedChange?:(checked: boolean) => void

onCheckedChange Type is a function , And is an optional type

When the event is triggered, it will call onChange Callback function for , In the callback function onCheckedChange function
But because onCheckedChange Is an optional type , So you can't call , Otherwise error—— Can't call could be “ Undefined ” The object of
We can use ?. To deal with the problem , When the component is passed in onCheckedChange Do not call

value={checked ? 1 : 0}
onChange={num => onCheckedChange?.(!!num)}
版权声明:本文为[TA_ WORLD]所创,转载请带上原文链接,感谢。