在我的react应用程序中,我有一个Card
组件:
function Card({name, note, folder, tag}) {
const typeHandler;
return (
<div className="card">
<FontAwesomeIcon icon={typeHandler} className="icon"/>
<h3 className="text">{name}</h3>
</div>
)
}
如果当我调用卡组件时,它有一个folder
JSX属性,我希望图标参数等于folder
,如下所示:
<Card name="Folder" folder/>,
如果它的(而不是文件夹(是tag
,那么图标将是tag
,我有更多的if else-if条件。我怎么能做那种事?
FontAwesomeIcon图标只是一个字符串
我以前试过:
function Card({name, note, folder, tag}) {
const typeHandler = () => {
if (note) {
return 'sticky-note'
}
else if (folder) {
return 'folder'
}
else if (tag) {
return 'tag'
}
}
return (
<div className="card">
<FontAwesomeIcon icon={typeHandler} className="icon"/>
<h3 className="text">{name}</h3>
</div>
)
}
您可以更新父组件,并将icon
道具作为字符串传递,该字符串的图标名小写,如:
父组件:
<Card name="Folder" icon="folder" />,
然后更新卡组件,如:
卡片组件:
import { library } from '@fortawesome/fontawesome-svg-core';
import { FontAwesomeIcon } from '@fortawesome/react-fontawesome';
import { faFolder, faTag, faBars, faStickyNote } from '@fortawesome/free-solid-svg-icons';
library.add(faFolder, faTag, faBars, faStickyNote)
export default function Card({ name, note, icon }) {
const typeHandler = name => {
switch (name) {
case "folder":
icon = faFolder; break;
case "tag":
icon = faTag; break;
default:
icon = faTag; break;
}
return { icon };
};
return (
<div className="card">
<FontAwesomeIcon {...typeHandler(icon)} className="icon" />
<h3 className="text">{name}</h3>
</div>
);
}
Codesandbox演示
假设,您只需将其中一个字段传递给Card,您可以使用rest spread语法,只需传递图标默认值,以防没有任何内容传递
function Card({name, note, ...rest}) {
return (
<div className="card">
<FontAwesomeIcon icon={rest[0] || 'defaultIcon'} className="icon"/>
<h3 className="text">{name}</h3>
</div>
)
}
您可以为此使用三元表达式,只要将它们放在大括号中即可。例如,如果你想设置图标参数,你可以写这样的东西:
<FontAwesomeIcon icon={folder ? folder : “other-icon”} ... />
这相当于使用一个典型的else语句来表示:如果文件夹不为null,则将图标设置为文件夹,否则将其设置为"其他图标"。
希望这能有所帮助!