Skip to content

Commit 780a9fe

Browse files
在 DirectImage 组件中引入 Next.js 的 Image 组件,添加宽度和高度属性,优化图片加载体验,并移除错误处理逻辑以简化代码结构。
1 parent 92bcb54 commit 780a9fe

File tree

1 file changed

+7
-5
lines changed

1 file changed

+7
-5
lines changed

src/components/DirectImage.js

Lines changed: 7 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -9,10 +9,13 @@
99
*/
1010

1111
import { useState, useEffect } from 'react'
12+
import Image from 'next/image'
1213

1314
export default function DirectImage({
1415
src,
1516
alt,
17+
width,
18+
height,
1619
className = '',
1720
style,
1821
loading = 'lazy',
@@ -24,12 +27,10 @@ export default function DirectImage({
2427
}) {
2528
const [imgSrc, setImgSrc] = useState(src)
2629
const [isLoading, setIsLoading] = useState(true)
27-
const [hasError, setHasError] = useState(false)
2830

2931
// 当 src 改变时重置状态
3032
useEffect(() => {
3133
setImgSrc(src)
32-
setHasError(false)
3334
setIsLoading(true)
3435
}, [src])
3536

@@ -40,29 +41,30 @@ export default function DirectImage({
4041

4142
const handleError = (e) => {
4243
console.error(`图片加载失败: ${src}`)
43-
setHasError(true)
4444
setImgSrc(fallback)
4545
setIsLoading(false)
4646
onError?.(e)
4747
}
4848

4949
return (
5050
<div className={`relative inline-block ${className}`} style={style}>
51-
<img
51+
<Image
5252
{...props}
5353
src={imgSrc}
5454
alt={alt}
55+
width={width || 800}
56+
height={height || 600}
5557
loading={loading}
5658
onLoad={handleLoad}
5759
onError={handleError}
60+
unoptimized // 关键:不使用 Next.js 的图片优化,直接加载原图
5861
className={`
5962
${isLoading && showLoading ? 'opacity-0' : 'opacity-100'}
6063
transition-opacity duration-300 ease-in-out
6164
${className}
6265
`}
6366
style={{
6467
...style,
65-
display: 'block',
6668
maxWidth: '100%',
6769
height: 'auto'
6870
}}

0 commit comments

Comments
 (0)