反应 bootstrap toast 位置打字稿错误

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

嗨,我正在尝试创建一个返回 React Bootstrap Toast 和 Toast 容器的组件,但收到打字稿错误。

const Notification = (props: {
variant: string,
header: string,
message: string,
position: string
}) => {
const [show, setShow] = useState(true);


return (
    <ToastContainer
      className="mt-4 pt-5"
    //   position={"top-center"}
      position={props.position}
      style={{ zIndex: 1 }}
    >
      <Toast
        onClose={() => setShow(false)}
        show={show}
        delay={7000}
        autohide
        bg={props.variant}
      >
        <Toast.Header closeButton={false}>
          <strong className="text-center">{props.header}</strong>
        </Toast.Header>
        <Toast.Body className="text-white text-center">{props.message}</Toast.Body>
      </Toast>
    </ToastContainer>
)
}

所以我就进去了

<Notification
    variant={"success"}
    header={"Success"}
    message={"Item successfully added to cart."}
    position={"top-center"}
  />

一切都像 props.message、props.variant 等一样工作。由于某种原因,尽管我收到以下位置错误。

类型“string”不可分配给类型“ToastPosition |”未定义'.ts(2322) ToastContainer.d.ts(5, 5):预期类型来自属性“position”,该属性在类型“IntrinsicAttributes & Omit”上声明,“ref"> & { ...; }, BsPrefixProps<...> & ToastContainerProps> & BsPrefixProps<...> & ToastContainerProps & { ...; }' (属性)ToastContainerProps.position?:ToastPosition |未定义

代码仍然有效(它从道具中获取“顶部中心”并将其正确放置),但它给出了类型错误。我知道它说它不能是字符串或未定义。我不明白为什么这种情况与 bg={props.variant} 不同。在这两种情况下都有一个默认值,并且它被更改为 prop。我什至尝试放入 位置={props.位置? props.position : "top-center"} 认为可能会修复它,但它仍然有相同的错误。

reactjs typescript typescript-typings react-bootstrap
1个回答
0
投票

position
ToastContainer
的类型是
ToastPosition | undefined
,而不是字符串。

要修复此问题,请在通知组件的类型声明中将

position: string
替换为
position?: ToastPosition
。问号使 prop 成为可选,从而添加
undefined

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