React&Ts 组件传入可选函数,undefined问题处理
组件
props
类型定义
interface PinProps extends React.ComponentProps<typeof Rate> {
checked:boolean,
onCheckedChange?:(checked: boolean) => void
}
onCheckedChange
类型是一个函数,并且是可选类型
当触发事件的时候就会调用onChange
的回调函数,在回调函数中又调用了onCheckedChange
函数
但是因为onCheckedChange
是可选类型,所以不能直接调用,否则会出现error——不能调用可能是“未定义”的对象
我们可以使用?.
来处理问题,当组件中为传入onCheckedChange
时就不调用
<Rate
count={1}
value={checked ? 1 : 0}
onChange={num => onCheckedChange?.(!!num)}
{...restProps}
/>