ant-design/components/icon/IconFont.tsx

57 lines
1.5 KiB
TypeScript
Raw Normal View History

2018-08-15 17:21:02 +08:00
import Icon, { IconProps } from './index';
import * as React from 'react';
const customCache = new Set<string>();
export interface CustomIconOptions {
2018-08-21 17:52:41 +08:00
scriptUrl?: string;
extraCommonProps?: { [key: string]: any };
}
2018-08-15 17:21:02 +08:00
export default function create(options: CustomIconOptions = {}): React.SFC<IconProps> {
2018-08-21 18:41:35 +08:00
const { scriptUrl, extraCommonProps = {} } = options;
2018-08-15 17:21:02 +08:00
/**
* DOM API required.
* Make sure in browser environment.
* The Custom Icon will create a <script/>
* that loads SVG symbols and insert the SVG Element into the document body.
*/
if (typeof document !== 'undefined' && typeof window !== 'undefined'
&& typeof document.createElement === 'function'
2018-08-21 17:52:41 +08:00
&& typeof scriptUrl === 'string' && scriptUrl.length
2018-08-21 18:41:35 +08:00
&& !customCache.has(scriptUrl)
2018-08-15 17:21:02 +08:00
) {
const script = document.createElement('script');
2018-09-29 16:45:57 +08:00
script.setAttribute('src', scriptUrl);
2018-08-21 18:41:35 +08:00
script.setAttribute('data-namespace', scriptUrl);
customCache.add(scriptUrl);
2018-08-15 17:21:02 +08:00
document.body.appendChild(script);
}
const Iconfont: React.SFC<IconProps> = (props) => {
2018-09-03 12:07:28 +08:00
const { type, children, ...restProps } = props;
2018-08-15 17:21:02 +08:00
// component > children > type
let content = null;
if (props.type) {
2018-08-21 18:41:35 +08:00
content = <use xlinkHref={`#${type}`} />;
}
2018-09-03 12:07:28 +08:00
if (children) {
content = children;
}
2018-08-15 17:21:02 +08:00
return (
<Icon
2018-09-03 12:07:28 +08:00
{...restProps}
2018-08-15 17:21:02 +08:00
{...extraCommonProps}
>
{content}
</Icon>
);
};
Iconfont.displayName = 'Iconfont';
return Iconfont;
}