React-TypeScript:无法调用可能是“未定义”的对象

时间:2020-06-24 10:58:51

标签: typescript react-typescript

我正在创建一个Alert组件。对于样式,我使用样式组件。对于打字稿,我放了道具any。我的警报组件工作正常。还有Looks like this。一旦添加界面道具,我就会收到很多错误。第一个错误是Cannot invoke an object which is possibly 'undefined'

这是我使用警报组件的父组件。

 <button
        style={{ color: "red" }}
        onClick={() =>
          Alert({
            id: "sign-in-fail-alert",
            title: "Good Job!",
            alertType: "success",
            onConfirm: () => setValue("click"),
            children: <div>You clicked the button! </div>
          })
        }
      >
        Show alert!
      </button>

这是我的警报组件。在Alert组件内部,创建了Modal,然后将其传递给Alert变量。我的警报变量的界面工作正常。我的模态界面出现错误。

import React from "react";
import ReactDOM from "react-dom";
import styled from "styled-components";
import { Button } from "components/buttons";
import { CloseIcon } from "assets/icons";
export const Container = styled.div`
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background-color: #000000e0;
  position: fixed;
  z-index: 3;
  display: flex;
  flexdirection: row;
  justifycontent: center;
  alignitems: center;
  aligncontent: center;
`;
export const ModalOverlay = styled.div`
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.8);
  cursor: pointer;
  z-index: 1;
`;
export const ModalClose = styled.button`
  position: absolute;
  top: 20px;
  right: 20px;
  transition: transform 250ms ease-in-out;
  transform-origin: 50% 50%;
  &:hover {
    transform: rotate(180deg);
  }
`;
export const IconContainer = styled.div`
  position: relative;
  z-index: 2;
  top: 6%;
  left: 47%;
  box-sizing: content-box;
  border-radius: 50%;
`;
export const ModalBox = styled.div`
  position: relative;
  width: 40%;
  padding: 1.25em;
  border: none;
  margin: 10% 10% 10% 25%;
  box-sizing: border-box;
  border-radius: 10px;
  background-color: white;
  cursor: auto;
  z-index: 2;
`;
export const Confirm = styled(Button)`
  position: relative;
  top: 100%;
  left: 50%;
`;
export const Title = styled.h1`
  position: relative;
  top: 40%;
  font-size: 50px;
  text-align: center;
  color: ${({ theme }) => theme.textColor};
`;

export const Children = styled.h1`
  position: relative;
  top: 40%;
  font-size: 20px;
  text-align: center;
  color: ${({ theme }) => theme.textColor};
`;

export interface IModal {
  title: string;
  onClose?: () => void;
  onCancel?: () => void;
  onConfirm?: () => void;
  children?: JSX.Element | string;
  icon?: JSX.Element;
  alertType?: "success" | "error" | "warning" | "info" | "question";
}
export const Modal = ({
  title,
  children,
  onClose,
  onCancel,
  onConfirm,
  icon,
  alertType
}:  IModal) => { // If I type any it works fine
  const handleCancel = () => {
    onCancel(); //Getting error from here
    onClose(); //Getting error from here
  };
  const handleConfirm = () => {
    onConfirm(); //Getting error from here
    onClose(); //Getting error from here
  };
  return (
    <Container>
      <ModalOverlay onClick={onClose} />
      <ModalBox>
        <ModalClose onClick={onClose}>
          <CloseIcon />
        </ModalClose>
        <Title>{title}</Title>
        <IconContainer>
          {icon ? (
            icon
          ) : alertType === "success" ? (
            <CloseIcon />
          ) : alertType === "error" ? (
            <p>error</p>
          ) : alertType === "warning" ? (
            <p>warning</p>
          ) : alertType === "info" ? (
            <p>info</p>
          ) : alertType === "question" ? (
            <p>question</p>
          ) : null}
        </IconContainer>
        <Children> {children}</Children>
        {onCancel && <Button onClick={handleCancel}>Cancel</Button>}
        {onConfirm && <Confirm onClick={handleConfirm}>Confirm</Confirm>}
      </ModalBox>
    </Container>
  );
};

export interface IAlert {
  title: string;
  children?: JSX.Element | string;
  id: string;
  alertType: string;
  onCancel?: () => void;
  onConfirm?: () => void;
}


export const Alert = ({
  title,
  children,
  id,
  alertType,
  onCancel,
  onConfirm
}: IAlert) => {
  // search the DOM for an element with the same ID and remove it
  const removeElement = () => document.getElementById(id)?.remove();
  const createElement = () => {
    const container = document.createElement(`div`);
    container.setAttribute(`class`, "alert");
    container.setAttribute(`id`, id);
    document.body.appendChild(container);
    ReactDOM.render(
      <Modal
        title={title}
        alertType={alertType}
        onCancel={onCancel}
        onConfirm={onConfirm}
        onClose={removeElement}
      >
        {children}
      </Modal>,
      container
    );
  };
  return createElement();
};

1 个答案:

答案 0 :(得分:0)

您在类型上定义了可选的属性,这就是为什么获得编译器消息的原因。如果您删除?onCancel属性后面的onConfirm,则它们将不再是可选的,并且不会收到错误消息。

export interface IAlert {
  title: string;
  children?: JSX.Element | string;
  id: string;
  alertType: string;
  onCancel: () => void;
  onConfirm: () => void;
}

如果可以更改接口,则至少必须在调用它们之前验证它们是否存在,例如:

const { onConfirm } = this.props;
onConfirm && onConfirm();

需要注意的一点是,children属性不是必需的,它们是React组件的标准属性,因此无需定义这些属性