能否将组件或图片作为Props传递?Button组件自定义图标需求
可以将组件作为Props传递,实现自定义图标需求
当然可以把组件或元素作为Props传递,这在React里是很常见的自定义组件方式,刚好能解决你想替换Button里箭头为自定义图片/图标的需求。下面是针对你代码的具体修改方案:
修改Button组件
调整组件的Props,新增一个icon参数,默认值设为你原来的ArrowRight组件,这样不传入自定义图标时仍保持原有逻辑。同时处理组件和普通元素(比如img)两种传入场景:
import { useState, cloneElement } from 'react'; import ArrowRight from './ArrowRight'; // 保持原有的组件导入 import styles from './Button.module.css'; export default function Button({ text, icon: Icon = ArrowRight }) { const [isHovered, setIsHovered] = useState(false); const fillColor = isHovered ? "white" : "black"; return ( <div> <button className={styles.button} onMouseEnter={() => setIsHovered(true)} onMouseLeave={() => setIsHovered(false)} > {text} <span className={styles.rightArrow}> {/* 区分传入的是组件还是DOM元素 */} {typeof Icon === 'function' ? ( // 如果是组件,传递fill属性适配hover颜色 <Icon fill={fillColor} /> ) : ( // 如果是img等元素,通过cloneElement修改样式实现变色 cloneElement(Icon, { style: { ...Icon.props.style, filter: isHovered ? 'brightness(0) invert(1)' : 'none' } }) )} </span> </button> </div> ); }
几种使用场景示例
- 保留原有箭头(不传入icon)
<Button text="提交表单" />
- 传入自定义图标组件
// 先定义你的自定义图标组件 function CustomStarIcon({ fill }) { return ( <svg fill={fill} viewBox="0 0 24 24"> <path d="M12 17.27L18.18 21l-1.64-7.03L22 9.24l-7.19-.61L12 2 9.19 8.63 2 9.24l5.46 4.73L5.82 21z" /> </svg> ); } // 使用时传入组件 <Button text="收藏" icon={CustomStarIcon} />
- 传入图片作为图标
<Button text="查看详情" icon={<img src="/assets/custom-arrow.png" alt="箭头图标" width="16" height="16" />} />
关键说明
- 用
icon: Icon = ArrowRight的写法,给Props设置默认值,确保原有代码无需改动就能正常运行。 - 区分组件和DOM元素的原因是:组件可以直接传递props(比如fill),而img这类元素需要通过
cloneElement修改样式来实现hover变色效果。
内容的提问来源于stack exchange,提问作者Cloud
相关产品推荐
相关产品推荐

