reactjs - 带有图标组件的按钮
问题描述
我有一个<Button />
组件和一个<Icon/>
组件。
我尝试实现一个带有图标的按钮。
故事Button.jsx
:
import React from "react";
import { storiesOf } from "@storybook/react";
import Button from "../components/Button";
import Icon from "../components/Icon/Index";
import { iconTypes } from "../components/Icon/Index";
storiesOf("Button/Primary", module)
.add("With icon", () => (
<Button><Icon type={iconTypes.arrowRight}/></Button>
))
效果很好,但我希望带有图标的按钮的 api 是-
<Button icon={icons.arrow}>Click Me</Button>
我怎样才能做到这一点?
故事Icon.jsx
:
import React from "react";
import { storiesOf } from "@storybook/react";
import Icon from "../components/Icon/Index";
import { iconTypes } from "../components/Icon/Index";
storiesOf("Icon", module)
.add("Arrow Right", () => (
<Icon type={iconTypes.arrowRight}>
</Icon>
))
.add("Arrow Left", () => (
<Icon type={iconTypes.arrowLeft}>
</Icon>
));
<Button />
组件:
import React from 'react';
import { css, cx } from 'emotion';
import colors from '../styles/colors';
export default function Button({
children,
...props
}) {
const mergedStyles = cx(
// css
);
// other css stuff
return (
<button {...props} disabled={disabled} className={mergedStyles}>
{children}
</button>
);
和<Icon />
组件:
import React from "react";
import { css } from 'emotion';
import ArrowRight from "./arrow-right2.svg";
import ArrowLeft from "./arrow-left2.svg";
export const iconTypes = {
arrowRight: 'ARROW_RIGHT',
arrowLeft: 'ARROW_LEFT',
}
const iconSrc = {
ARROW_RIGHT: ArrowRight,
ARROW_LEFT: ArrowLeft,
}
const circleStyles = css({
width: 24,
height: 24,
borderRadius: "50%",
backgroundColor: "#f7f7f9",
display: "flex",
justifyContent: "center"
});
export default function Icon({ type }) {
return (
<div className={circleStyles}>
<img src={iconSrc[type]} />
</div>
)
};
任何帮助,将不胜感激。
解决方案
import React from 'react';
import {css, cx} from 'emotion';
import colors from '../styles/colors';
//import your ICON component & make sure your path is right
import Icon from "./../Icon";
export default function Button({
children,
disabled,
icon,
...props
}) {
const mergedStyles = cx(//your css);
return (
<button {...props} disabled={disabled} className={mergedStyles}>
// If icon prop is provided then render ICON component
{icon && <Icon type={icon}/>}
//Other children
{children}
</button>
);
}
推荐阅读
- chart.js - 使用 Chart.js 添加水平十字准线
- python - PYMC3 属性错误 get_default_varnames
- swift - 快速推送通知以与 Intranet 中的应用程序通信服务器的最佳选择
- r - 如何在geom_bar ggplot2中添加第二个栏
- html - 滚动到页面底部时无法访问固定导航栏
- javascript - multer.memoryStorage() 将 req.file 返回为未定义
- python - 如何使用 Selenium - Python 从网站上我的项目的另一个目录上传图像?
- python - 正则表达式列表中的整数总和
- tensorflow - 如何用 tensorflow 训练小 yolov2?
- python - 运行 FancyArrowPatch 函数后如何获取坐标?