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;
2019-06-24 11:29:58 +08:00
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.
*/
2018-12-07 16:17:45 +08:00
if (
typeof document !== 'undefined' &&
typeof window !== 'undefined' &&
typeof document.createElement === 'function' &&
typeof scriptUrl === 'string' &&
scriptUrl.length &&
!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);
}
2018-12-07 16:17:45 +08:00
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 (
2018-12-07 16:17:45 +08:00
<Icon {...restProps} {...extraCommonProps}>
2018-08-15 17:21:02 +08:00
{content}
</Icon>
);
};
Iconfont.displayName = 'Iconfont';
return Iconfont;
}