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

时间:2020-03-15 23:42:09

标签: javascript reactjs typescript material-ui react-component

我试图创建一个自定义反应物料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)

1 个答案:

答案 0 :(得分:1)

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