背景:当我们在react
中封装组件并复用时,会传不同的props
,那么自然有些props
是不需要传的,所以在定义interface
的时候需要加个问号。但这也就引来了标题的报错!
模拟一下报错代码:
// 父组件
const handleVisible () => {
}
export default function Father(props: IProps) {
return (
<Child/>
<Child handleVisible={handleVisible}/>
)
}
// 子组件
interface IProps {
handleVisible?: () => void
}
export default function Child(props: IProps) {
reutrn (
// xxxxxxx
)
const getList = async () => {
// 假设进行异步请求之后会调用父组件的``handleVisible``方法
const res = await getlist()
props.handleVisible() // 这段代码这个时候会报错!!!因为我们调用了两次子组件,只有一个传了handleVisible方法,所以ts不会让你执行
}
}
解决方法也很简单:
1.先检查是否有该方法再执行。 即
props.handleVisible && props.handleVisible()
2.类型断言。 即
props.handleVisible!()