TS错误-创建自定义React Alert组件

问题描述 投票:0回答:1

我正在尝试创建一个自定义反应物料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)
javascript reactjs typescript material-ui react-component
1个回答
0
投票

Alert只能接受有限数量的字符串或未定义的字符串,因此必须明确指出您的传递字符串属于这种类型。

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之一,并且不应抛出错误。

© www.soinside.com 2019 - 2024. All rights reserved.