React+TypeScript传递接口类型Props给组件报错问题求助
React+TypeScript传递整个接口对象给组件时的类型错误
我正在学习React和TypeScript,开发一个用户录入Demo(输入姓名与年龄),提交无效数据时需显示ErrorModal组件。定义了IError接口包含errorTitle、errorMessage及可选的onConfirmError方法,使用useState管理error状态。尝试将整个error对象传递给ErrorModal时,出现类型错误:
Type '{ error: IError; }' is not assignable to type 'IntrinsicAttributes & IError'. Property 'error' does not exist on type 'IntrinsicAttributes & IError'.
目前拆分传递单个Props可解决问题,但希望直接传递整个接口实例,求简便修复方法或正确实现方式。
相关代码
IError接口定义
export interface IError { errorTitle: string; errorMessage: string; onConfirmError?(): void; }
useState及错误设置逻辑
const [error, setError] = useState<IError | null | undefined>(); const addUserHandler = (event: any) => { event.preventDefault(); if(enteredUsername.trim().length === 0 ){ setError({ errorTitle: 'Invalid Username', errorMessage: 'Username must be more than 4 characters', }) return; } }
ErrorModal组件代码
type Props = IError; const ErrorModal: React.FC<Props> = (props) => { return ( <div> <div className={styles.backdrop} onClick={props.onConfirmError}/> <Card className={styles.modal}> <header className={styles.header}> <h2>{props.errorTitle}</h2> </header> <div className={styles.content}> <p>{props.errorMessage}</p> </div> <footer className={styles.actions}> <Button onClick={props.onConfirmError}>OK</Button> </footer> </Card> </div> ) } export default ErrorModal;
错误的传递方式
{error && <ErrorModal error={error} onConfirmError={errorHandler}/>}
解决方案
方案1:使用对象展开运算符(推荐)
直接展开error对象的所有属性,同时单独传入onConfirmError(覆盖或补充error对象中缺失的回调),完全匹配组件的Props类型:
{error && <ErrorModal {...error} onConfirmError={errorHandler} />}
这种方式无需修改组件代码,写法简洁,符合React组件Props传递的最佳实践。
方案2:修改组件Props类型以接受整个error对象
如果想保留error={error}的传递写法,可调整ErrorModal的Props定义:
// 更新Props类型 type Props = { error: IError; onConfirmError?: () => void; }; // 组件内从props.error中访问属性 const ErrorModal: React.FC<Props> = (props) => { return ( <div> <div className={styles.backdrop} onClick={props.onConfirmError} /> <Card className={styles.modal}> <header className={styles.header}> <h2>{props.error.errorTitle}</h2> </header> <div className={styles.content}> <p>{props.error.errorMessage}</p> </div> <footer className={styles.actions}> <Button onClick={props.onConfirmError}>OK</Button> </footer> </Card> </div> ); };
方案3:拆分错误状态与回调(逻辑优化)
将onConfirmError从IError接口中移除,让error状态仅存储纯错误信息,回调由父组件单独传递,职责更清晰:
// 调整IError接口 export interface IError { errorTitle: string; errorMessage: string; } // useState定义不变 const [error, setError] = useState<IError | null | undefined>(); // 传递组件时 {error && <ErrorModal {...error} onConfirmError={errorHandler} />}
内容的提问来源于stack exchange,提问作者chucknor
相关产品推荐
相关产品推荐

