You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何复用ReactJS Emoction组件 按需传入FontAwesome图标并设置默认值

实现步骤

1. 重构Emoction组件支持参数传入

修改emoction.js代码如下:

import { faHeart, faHeartBroken } from "@fortawesome/free-solid-svg-icons";
import { FontAwesomeIcon } from "@fortawesome/react-fontawesome";
import React from 'react';

// 接收icon参数,默认值设为faHeartBroken,满足无参调用需求
const Emoction = ({ icon = faHeartBroken }) => {    
    return (
        <FontAwesomeIcon icon={icon} />
    );
};

export default Emoction;

改造后你可以直接删除单独的emoction_hb.js文件,不需要再维护多份表情组件。

2. 调整整合页代码复用单组件

修改expanded_content.js代码如下:

import Emoction from "../emoctions/emoctions";
import styled from "@emotion/styled";
import { faHeart, faHeartBroken } from "@fortawesome/free-solid-svg-icons";
import React from 'react';

const Merged = styled.div`
    display: flex;
    flex-direction: row;
    justify-content: flex-start;
`;

const ExpandedContent = () => {
    return(
      <div>
        <Merged>
            {/* 传入faHeart渲染爱心表情 */}
            <Emoction icon={faHeart}/>
            {/* 传入faHeartBroken渲染心碎表情 */}
            <Emoction icon={faHeartBroken}/>
            {/* 不需要传参时默认渲染心碎表情,写法如下: */}
            {/* <Emoction/> */}
        </Merged>
      </div>
    )
};
    
export default ExpandedContent;

调整后渲染效果和你之前的实现完全一致,后续如果需要新增其他表情,只需要导入对应的FontAwesome图标,直接传给Emoction组件的icon参数即可,不需要再新建单独的组件文件。

内容的提问来源于stack exchange,提问作者everestial

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.02 10:18:04