NextJS Image组件title属性无法生效,求可行解决方案
Next.js Image 组件添加title属性的解决办法
Next.js 的 Image 组件确实没有直接支持 title 属性,这里有几个实用的解决办法:
用容器元素包裹,给容器加title
这是最直接简单的方式,用 span、div 这类元素把 Image 包起来,给容器设置 title 属性,鼠标悬停时一样会显示提示文本:<span title="ChatGPT"> <Image src={logoChatGPT} alt="ChatGPT" width={24} height={24} className='ml-2' /> </span>通过onLoad事件给原生img设置title
Next.js Image 最终会渲染出原生的 img 标签,我们可以利用 onLoad 事件获取到这个元素,手动给它设置 title:<Image src={logoChatGPT} alt="ChatGPT" width={24} height={24} className='ml-2' onLoad={(e) => { e.currentTarget.title = "ChatGPT"; }} />自定义封装带title的Image组件
如果项目里很多地方需要带title的图片,可以自己封装一个复用组件,以后直接用这个组件就行:import Image from 'next/image'; const ImageWithTitle = ({ title, ...props }) => { return ( <span title={title}> <Image {...props} /> </span> ); }; // 使用示例 <ImageWithTitle src={logoChatGPT} alt="ChatGPT" title="ChatGPT" width={24} height={24} className='ml-2' />
内容的提问来源于stack exchange,提问作者Harsha M V
相关产品推荐
相关产品推荐

