【问题标题】:Typescript React/ styled-components - passing function as prop to component throws error on missing typeTypescript React / styled-components - 将函数作为道具传递给组件会在缺少类型时引发错误
【发布时间】:2021-12-28 08:17:53
【问题描述】:

我收到重载匹配错误,但我不明白,因为昨天没有收到此错误,当我尝试在另一个组件或订单页面中添加另一个 onClick 函数时,也会发生这种错误

image of error

代码;

import React, { MouseEventHandler } from 'react'

import { Container, Image } from './styles'

interface ImageFullscreen {
  path?: string
  shown: boolean
  close: MouseEventHandler
}

const ImageFullscreen: React.FC<ImageFullscreen> = ({
  path = 'https://via.placeholder.com/1920x1080?text=Imagem+Placeholder+Das+Postagens',
  close,
  shown,
}) => {
  const handleMapViewClose: MouseEventHandler<HTMLDivElement> = e => {
    const source = (e.target as HTMLDivElement & HTMLImageElement).src
    if (source === undefined) {
      close(e)
    }
  }

  return (
    <Container display={shown} onClick={handleMapViewClose}>
      <Image src={path} alt='ImageFullscreen' />
    </Container>
  )
}

export default ImageFullscreen

容器代码

import styled from 'styled-components'
import { fadeIn } from 'styles/keyframes'

interface Container {
  display: boolean
}

export const Container = styled.div<Container>`
  position: fixed;
  width: 100vw;
  height: 100vh;
  background-color: rgba(0, 0, 0, 0.8);
  top: 0;
  left: 0;
  z-index: 1000;
  display: ${props => (props.display ? 'flex' : 'none')};
  align-items: center;
  justify-content: center;
  padding: 50px;
  animation: ${fadeIn} 500ms 1;
`

export const Image = styled.img`
  max-height: 100%;
  max-width: 100%;
  min-height: 600px;
`

【问题讨论】:

  • 你能提供给我们这个容器的代码吗?也许是您创建样式组件的方式谢谢
  • 对不起,我添加了容器创建
  • 那么,它现在工作了吗?
  • 不一样,我添加了有问题的容器创建

标签: reactjs typescript styled-components


【解决方案1】:

我认为你的界面名称有问题,它与你的组件相同,也许你可以更改名称,它会起作用。

类似这样的:

interface IContainer {
  display: boolean
}
export const Container = styled.div<IContainer>`...`

【讨论】:

  • 这可能是真的! Lucas 的样式化组件 'Container' 与接口 'Container' 命名相同
【解决方案2】:

卢卡斯,如果你尝试

const handleMapViewClose = ( e : React.MouseEvent<HTMLDivElement> ) => {
    const source = (e.target as HTMLDivElement & HTMLImageElement).src
    if (source === undefined) {
      close(e)
    }
  }

有效吗?


我认为您可能拼错了事件接口名称?

【讨论】:

    猜你喜欢
    • 2021-10-05
    • 2018-09-04
    • 2021-08-04
    • 1970-01-01
    • 2019-10-07
    • 2020-03-12
    • 2022-10-13
    • 2022-06-19
    • 2018-12-01
    相关资源
    最近更新 更多