我正在尝试创建一个自定义 react Material ui 警报组件,我可以通过简单地将文本和严重性作为参数传递来在不同的页面上调用它。我正在尝试使用它:
export default function CustomAlert(severity: string, text: string){
<Alert style={{width:'50%'}} severity={severity}> {text}</Alert>
}
但我在第一个严重性单词 severity={severity}
上不断收到错误:
Type 'string' is not assignable to type '"error" | "success" | "info" | "warning" | undefined'.ts(2322)
Alert.d.ts(25, 3): The expected type comes from property 'severity' which is declared here on type 'IntrinsicAttributes & AlertProps'
我该如何解决这个问题?或者是否有其他方法可以自定义此组件?
编辑:我仍然无法在我的其他页面中使用它:
function StatusMessage(){
if (isRemoved){
return (
<Alert style={{width:'25%'}} severity="success"> User Removed</Alert>
)
}
else{
if(errorMessage!=''){
if (errorMessage.includes(`Couldn't find user`)){
return (
<div>
{/* <Alert style={{width:'25%'}} severity="error"> Couldn't Find User</Alert> */}
<CustomAlert></CustomAlert>
</div>
)
}
}}
}
我在 CustomAlert 上收到以下错误:
JSX element type 'void' is not a constructor function for JSX elements.ts(2605)
Type '{}' is not assignable to type '(IntrinsicAttributes & "success") | (IntrinsicAttributes & "info") | (IntrinsicAttributes & "warning") | (IntrinsicAttributes & "error")'.
Type '{}' is not assignable to type '"error"'.ts(2322)
最佳答案
Alert
只能接受有限数量的字符串或未定义的字符串,因此您必须明确说明您的 pass 字符串属于这种类型。
type Severity = "error" | "success" | "info" | "warning" | undefined;
export default function CustomAlert(severity: Severity, text = "Sorry"){
<Alert style={{width:'50%'}} severity={severity}> {text}</Alert>
}
现在,TS 编译器知道 severity
将是联合类型 Severity
之一,并且不应该抛出错误。
关于javascript - TS 错误 - 创建自定义 react 警报组件,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60698786/