reactjs - 导入时道具类型出错,Ts(2322)
问题描述
有人能帮我吗?我将 TypeScript、StyledComponent 和 React 与 Create React App 一起使用。此错误发生在构建期间,无法消除。
// browser and terminal error
TypeScript error in ./src/index.tsx(4,1):
Type '{ alt: string; src: string; }' is not assignable to type 'IntrinsicAttributes'.
Property 'alt' does not exist on type 'IntrinsicAttributes'. TS2322
// ./src/components/Image/index.tsx
import React from 'react'
import Styled from 'styled-components/macro'
interface ImageInterface {
alt?: string | undefined
src: string
}
const Image = Styled.img`
max-width: 100%;
`
export default () => ({ alt, src }: ImageInterface) => (
<Image alt={alt || 'My alternative text'} src={src} />
)
// ./src/index.tsx
import React from 'react'
import Image from './components/Image'
<Image src="https://cjpatoilo.com/initify/artwork.png" />
// ./package.json
"dependencies": {
"@types/jest": "^24.0.18",
"@types/node": "^12.7.5",
"@types/react": "^16.9.2",
"@types/react-dom": "^16.9.0",
"@types/react-router-dom": "^4.3.5",
"@types/styled-components": "^4.1.19",
"react": "^16.9.0",
"react-dom": "^16.9.0",
"react-router-dom": "^5.0.1",
"styled-components": "^4.3.2",
"typescript": "^3.6.3"
},
"devDependencies": {
"enzyme": "^3.10.0",
"enzyme-adapter-react-16": "^1.14.0",
},
我希望正常的图像编译组件没有错误
解决方案
问题可能在您的./src/components/Image/index.tsx
文件中。默认导出是返回组件的函数。但它被./src/index.tsx
当作一个函数组件来使用。
第一个选项是删除此包装功能:
// ./src/components/Image/index.tsx
export default ({ alt, src }: ImageInterface) => (
<Image alt={alt || 'My alternative text'} src={src} />
)
或者,调用此方法,然后将返回值用作组件。
// ./src/index.tsx
import Fn from './components/Image'
const Image = Fn();
<Image src="https://cjpatoilo.com/initify/artwork.png" />
推荐阅读
- sql-server - 如何判断当前会话是否持有锁?
- mysql - 将列作为日期类型从 CSV 导入 MySQL
- handlebars.js - 如何将自定义链接数据添加到 Branch.io 中的自定义 Deepview?
- node.js - 在浏览器中显示基线 h264 帧流
- c# - 如何抛出异常
- firebase - Firebase Android应用程序无法在物理手机上使用电子邮件和密码登录,只能在模拟器上登录
- docker - 无论如何要在docker中全局配置凭据规范文件吗?
- python - 如何在最大化、不可调整大小的 tkinter 窗口上取消隐藏任务栏?
- php - 为什么我在 htaccess 文件中的代码不起作用?
- c - select() 可以防止 read() 被中断吗?