ant-design/components/icon/IconFont.tsx

60 lines
1.6 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 {
namespace?: string;
prefix?: string;
2018-08-16 18:44:43 +08:00
url?: string;
extraCommonProps?: { [key: string]: any };
}
2018-08-15 17:21:02 +08:00
export default function create(options: CustomIconOptions = {}): React.SFC<IconProps> {
2018-08-16 18:44:43 +08:00
const { namespace, prefix = '', url, 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-16 18:44:43 +08:00
&& typeof url === 'string' && url.length
2018-08-15 17:21:02 +08:00
&& typeof namespace === 'string' && namespace.length
&& !customCache.has(namespace)
) {
const script = document.createElement('script');
2018-08-16 18:44:43 +08:00
script.setAttribute('src', `https://${url}.js`);
2018-08-15 17:21:02 +08:00
script.setAttribute('data-namespace', namespace);
customCache.add(namespace);
document.body.appendChild(script);
}
const Iconfont: React.SFC<IconProps> = (props) => {
2018-08-15 17:21:02 +08:00
const { type } = props;
2018-08-15 17:21:02 +08:00
// component > children > type
let content = null;
if (props.type) {
content = <use xlinkHref={`#${prefix}${type}`} />;
}
2018-08-15 17:21:02 +08:00
if (props.children) {
content = props.children;
}
2018-08-15 17:21:02 +08:00
return (
<Icon
{...props}
{...extraCommonProps}
>
{content}
</Icon>
);
};
Iconfont.displayName = 'Iconfont';
return Iconfont;
}