采纳答案成功!
向帮助你的同学说点啥吧!感谢那些助人为乐的人
老师好, 既然Button组件,要么是button 要么是a, 那么ButtonProps是不是可以设置为联合类型呢? 如下所示:
export type ButtonProps = NativeButtonProps | AnchorButtonProps
同学你好
这个场景下使用联合类型确实是更好的选项,甚至你可以使用一个类型收窄的方法让组件更加完美:
function isAnchorButton(props: ButtonProps): props is AnchorButtonProps { return 'href' in props; } const Button = (props: ButtonProps) => { if (isAnchorButton(props)) { // 这里 TypeScript 能够准确推断出 props 的类型是 AnchorButtonProps return <a href={props.href}>{props.children}</a> } // 这里会被推断为 NativeButtonProps return <button type={props.type}>{props.children}</button> }
非常感谢!
登录后可查看更多问答,登录/注册
设计,开发,测试,发布再到 CI/CD,从0到1造轮子
3.0k 9
1.8k 16
1.6k 12
2.0k 11
2.5k 11
购课补贴联系客服咨询优惠详情
慕课网APP您的移动学习伙伴
扫描二维码关注慕课网微信公众号