@2hats/react-native-vector-icons 中文文档教程

发布于 7年前 浏览 40 项目主页 更新于 3年前

React Native 的矢量图标

“特拉维斯” npm npm 问题统计

非常适合按钮、徽标和导航/标签栏。 易于扩展、设计和集成到您的项目中。

Bundled Icon Sets

浏览所有

Installation

  1. Run: $ npm install react-native-vector-icons --save
  2. For each platform (iOS/Android/Windows) you plan to use, follow one of the options for the corresponding platform.

iOS

Option: Manually

如果您想使用任何捆绑图标,您需要将图标字体添加到您的 Xcode 项目中。 只需按照以下步骤操作:

  • Browse to node_modules/react-native-vector-icons and drag the folder Fonts (or just the ones you want) to your project in Xcode. Make sure your app is checked under "Add to targets" and that "Create groups" is checked if you add the whole folder.
  • Edit Info.plist and add a property called Fonts provided by application (or UIAppFonts if Xcode won't autocomplete/not using Xcode) and type in the files you just added. It will look something like this:

XCode screenshot

注意:您需要在添加新字体后重新编译项目,同时确保它们也出现在Build Phases 中的Copy Bundle Resources 下。

如果您想使用 TabBar /NavigatorIOS集成或者使用getImageSource,那么需要在Libraries中添加RNVectorIcons.xcodeproj,添加libRNVectorIcons.aBuild PhasesLink Binary With Libraries有关如何执行此操作的更多信息和屏幕截图可在 React Native 文档中找到

Option: With CocoaPods

将以下内容添加到您的 Podfile 并运行 pod update

pod 'RNVectorIcons', :path => 'node_modules/react-native-vector-icons'

如上所述编辑 Info.plist

如果您在 Podfile 中使用 use_frameworks!,则需要在引导应用程序时通过执行 Icon.loadFont() 来动态加载图标字体.

Option: With rnpm

$ react-native link

注意:有些用户在使用此方法时遇到问题,如果您也是,请尝试其他方法之一。

Android

Option: With Gradle (recommended)

此方法的优点是可以从在构建时添加此模块,以便字体和 JS 始终同步,从而使升级变得轻松。

编辑 android/app/build.gradle(不是 android/build.gradle)并添加以下内容:

apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

要自定义要复制的文件,请添加以下内容:

project.ext.vectoricons = [
    iconFontNames: [ 'MaterialIcons.ttf', 'EvilIcons.ttf' ] // Name of the font files you want to copy
]

apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

Option: Manually

  • Copy the contents in the Fonts folder to android/app/src/main/assets/fonts (note lowercase font folder).
Integrating library for getImageSource and ToolbarAndroid support

这些步骤是可选,仅当您想使用 Icon.getImageSource 函数或在 Icon.ToolbarAndroid 组件中使用自定义图标时才需要。

  • Edit android/settings.gradle to look like this (without the +):
  rootProject.name = 'MyApp'

  include ':app'

  + include ':react-native-vector-icons'
  + project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')
  • Edit android/app/build.gradle (note: app folder) to look like this:
  apply plugin: 'com.android.application'

  android {
    ...
  }

  dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
  + compile project(':react-native-vector-icons')
  }
  • Edit your MainApplication.java (deep in android/app/src/main/java/...) to look like this (note two places to edit):
  package com.myapp;

  + import com.oblador.vectoricons.VectorIconsPackage;

  ....

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
        new MainReactPackage()
  +   , new VectorIconsPackage()
      );
    }

  }

注意:如果您使用的是 React Native (Android) <= 0.17,按照此说明操作

Option: With rnpm

$ react-native link

注意:有些用户在使用此方法时遇到问题,请尝试

OSX via react-native-desktop

  • Browse to node_modules/react-native-vector-icons and drag the folder Fonts to your project in Xcode. Make sure your app is checked under "Add to targets" and that "Create folder references" is checked.
  • Edit Info.plist and add a property called Application fonts resource path (or ATSApplicationFontsPath if Xcode won't autocomplete/not using Xcode) and type Fonts as the value.

注意:添加新字体后需要重新编译项目,还要确保 Fonts 文件夹也出现在 Copy Bundle 下构建阶段中的资源

Windows via react-native-windows

  • Open your solution in Visual Studio, right click the Assets folder in your solution, click Add Existing.
  • Browse to the node_modules\react-native-vector-icons\Fonts folder, select the required font files
  • Click the Add drop-down and select Add as Link.
  • Set Copy To Output Directory property of each font file to Copy if newer

注意:添加新字体后需要重新编译项目。

Web (with webpack)

在您的 webpack 配置文件中,添加一个部分到使用 url-loader(或 file-loader)处理 ttf 文件

{
  test: /\.ttf$/,
  loader: "url-loader", // or directly file-loader
  include: path.resolve(__dirname, "node_modules/react-native-vector-icons"),
},

然后在你的 JavaScript 入口点使用这些文件来获取捆绑的 url 并在你的页面中注入一个样式标签:

// Use prebuilt version of RNVI in dist folder
import Icon from 'react-native-vector-icons/dist/FontAwesome';

// Generate required css
import iconFont from 'react-native-vector-icons/Fonts/FontAwesome.ttf';
const iconFontStyles = `@font-face {
  src: url(${iconFont});
  font-family: FontAwesome;
}`;

// Create stylesheet
const style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
  style.styleSheet.cssText = iconFontStyles;
} else {
  style.appendChild(document.createTextNode(iconFontStyles));
}

// Inject stylesheet
document.head.appendChild(style);

Icon Component

你可以使用上面的捆绑图标之一或滚动你自己的自定义字体。

import Icon from 'react-native-vector-icons/FontAwesome';
const myIcon = (<Icon name="rocket" size={30} color="#900" />)

Properties

任何 文本属性 和以下内容:

Prop Description Default
size Size of the icon, can also be passed as fontSize in the style object. 12
name What icon to show, see Icon Explorer app or one of the links above. None
color Color of the icon. Inherited

Styling

因为 Icon 建立在Text 组件,大多数 style 属性 将按预期工作,你可能会发现玩这些很有用:

  • backgroundColor
  • borderWidth
  • borderColor
  • borderRadius
  • padding
  • margin
  • color
  • fontSize

注意:Android 上的 Text 目前不支持 border* 样式,要避免这种情况,只需包装您的 IconView

例如:

通过组合其中的一些你可以创建 star

Icon.Button Component

一个方便的组件,用于创建带有图标的按钮左边。

import Icon from 'react-native-vector-icons/FontAwesome';
const myButton = (
  <Icon.Button name="facebook" backgroundColor="#3b5998" onPress={this.loginWithFacebook}>
    Login with Facebook
  </Icon.Button>
);

const customTextButton = (
  <Icon.Button name="facebook" backgroundColor="#3b5998">
    <Text style={{fontFamily: 'Arial', fontSize: 15}}>Login with Facebook</Text>
  </Icon.Button>
);

buttons

Properties

任何 文本, TouchableHighlightTouchableWithoutFeedback 除了这些之外的属性:

Prop Description Default
color Text and icon color, use iconStyle or nest a Text component if you need different colors. white
size Icon size. 20
iconStyle Styles applied to the icon only, good for setting margins or a different color. {marginRight: 10}
backgroundColor Background color of the button. #007AFF
borderRadius Border radius of the button, set to 0 to disable. 5
onPress A function called when the button is pressed. None

Usage as PNG image/source object

将其插入到依赖位图图像而不是可缩放矢量图标的其他组件中的便捷方法。 如上所述采用参数 namesizecolor

Icon.getImageSource('user', 20, 'red').then((source) => this.setState({ userIcon: source }));

如需完整示例,请查看 TabBarExample 项目。

Usage with TabBarIOS

只需使用 Icon.TabBarItemIOS 而不是 TabBarIOS.Item。 这是一个扩展组件,其工作方式完全相同,但具有三个附加属性:

Prop Description Default
iconName Name of the default icon (similar to TabBarIOS.Item icon) None
selectedIconName Name of the selected icon (similar to TabBarIOS.Item selectedIcon). iconName
iconSize Size of the icon. 30
iconColor Color of the icon. None
selectedIconColor Color of the selected icon. iconColor

例如,用法请参见 Examples/TabBarExample 或下面的示例部分。 如果您要使用 TabBar 集成,请不要忘记如上所述导入并链接到该项目。

注意:使用iconColorselectedIconColor 需要属性renderAsOriginalIcon.TabBarItemIOS 上设置为 true

Usage with NavigatorIOS

使用 Icon.getImageSource 获取图像源对象并像使用 backButtonIconleftButtonIconrightButtonIcon 一样传递它.

注意:由于 NavigatorIOS 不会重新呈现新状态 和异步性质getImageSource 在图标呈现之前,您不能将它与 initialRoute 一起使用,但是通过 push 添加的任何视图都应该没问题。 最简单的方法是在渲染方法的开头添加一个 if 语句,如下所示:

  render() {
    if (!this.state.myIcon) {
      return false;
    }
    return (<NavigatorIOS ... />);
  }

Facebook 写道

开发属于开源社区 - React Native 团队未在其应用程序中使用。 这样做的结果是,目前积压了未解决的错误,使用它的人还没有加强对它的所有权。

使用 Navigator.NavigationBarreact-native-navbar

Usage with ToolbarAndroid

只需使用 Icon.ToolbarAndroid 而不是 React.ToolbarAndroid,这是底层 ToolbarAndroid 组件的组合,其工作方式相同,但任何 * icon 属性也采用 *iconName

Prop Description Default
logoName Name of the navigation logo icon (similar to ToolbarAndroid logo) None
navIconName Name of the navigation icon (similar to ToolbarAndroid navIcon) None
overflowIconName Name of the overflow icon (similar to ToolbarAndroid overflowIcon). none
actions Possible actions on the toolbar as part of the action menu, takes the additional arguments iconName, iconColor and iconSize. none
iconSize Size of the icons. 24
iconColor Color of the icons. black

例如用法请参阅 Examples/IconExplorer/index.android.js 或下面的示例部分。 如果您要使用 ToolbarAndroid 集成,请不要忘记如上所述导入并链接到该项目。

Custom Fonts

createIconSet(glyphMap, fontFamily[, fontFile])

根据 glyphMap 返回您自己的自定义字体,其中键是图标名称,值是 UTF-8 字符或其字符代码。 fontFamily 是字体的名称不是 文件名。 在 Font Book.app 或类似软件中打开字体以了解名称。 可选择传递第三个 fontFile 参数以获得 android 支持,它应该是资产文件夹中字体文件的路径。

import { createIconSet } from 'react-native-vector-icons';
const glyphMap = { 'icon-name': 1234, test: '∆' };
const Icon = createIconSet(glyphMap, 'FontName');

createIconSetFromFontello(config[, fontFamily[, fontFile]])

基于 fontello 配置文件创建自定义字体的便捷方法。 不要忘记如上所述导入字体并将 config.json 放在项目中方便的地方。

import { createIconSetFromFontello } from 'react-native-vector-icons';
import fontelloConfig from './config.json';
const Icon = createIconSetFromFontello(fontelloConfig);

createIconSetFromIcoMoon(config[, fontFamily[, fontFile]])

import { createIconSetFromIcoMoon } from 'react-native-vector-icons';
import icoMoonConfig from './config.json';
const Icon = createIconSetFromIcoMoon(icoMoonConfig);

确保您使用的是 IcoMoon 中的下载 选项,并使用您下载的.zip 中包含的.json 文件。 您还需要按照上述说明将 .ttf 字体文件导入到您的项目中。

iOS

您必须在 xcodeproj Resources 文件夹中手动引用您的 .ttf

Animation

React Native 带有一个很棒的动画库,名为 Animated。 要将它与图标一起使用,只需使用以下行创建一个动画组件:const AnimatedIcon = Animated.createAnimatedComponent(Icon)。 您还可以使用更高级别的动画库 react-native-animatable

Examples

IconExplorer

尝试 Examples/IconExplorer 文件夹中的 IconExplorer 项目,您还可以在那里搜索任何图标。

Screenshot of IconExplorer

Basic Example

import Icon from 'react-native-vector-icons/Ionicons';

function ExampleView(props) {
  return (<Icon name="ios-person" size={30} color="#4F8EF7" />);
}

TabBarIOS

TabBarExampleExamples/TabBarExample 文件夹中的代码> 项目。

import { View, Text, TabBarIOS } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';

function TabBarView(props) {
  return (
    <TabBarIOS>
      <Icon.TabBarItem
        title="Home"
        iconName="ios-home-outline"
        selectedIconName="ios-home"
        >
        <View style={styles.tabContent}><Text>Home Tab</Text></View>
      </Icon.TabBarItem>
    </TabBarIOS>
  );
}

ToolbarAndroid

import Icon from 'react-native-vector-icons/Ionicons';

function ToolbarView(props) {
  return (
    <Icon.ToolbarAndroid
      title="Home"
      titleColor="white"
      navIconName="md-arrow-back"
      onIconClicked={props.navigator.pop}
      actions={[
        { title: 'Settings', iconName: 'md-settings', iconSize: 30, show: 'always' },
        { title: 'Follow me on Twitter', iconName: 'logo-twitter', iconColor: "#4099FF", show: 'ifRoom' },
      ]}
      overflowIconName="md-more"
    />
  );
}

Inline Icons

import { Text } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';

function ExampleView(props) {
  return (<Text>Lorem <Icon name="ios-book" color="#4F8EF7" /> Ipsum</Text>);
}

Community examples

Generating your own icon set from a CSS file

如果您已经有了带有关联 CSS 文件的图标字体,那么您可以使用 generate-icon 脚本轻松生成图标集。

Example usage:

./node_modules/.bin/generate-icon path/to/styles.css --componentName=MyIcon --fontFamily=myicon > Components/MyIcon.js

Options

下面未列出的任何标志,如 --componentName--fontFamily,将被传递到模板。

-p, --prefix

CSS 选择器前缀 [默认:".icon-"]

-t, --template

lodash 格式的模板 [默认:"./template/iconSet.tpl"]

对于默认模板,请提供 --componentName--字体系列

-o, --output

将输出保存到文件,默认为 STDOUT

Changelog

Troubleshooting

The icons show up as a crossed out box on Android

  • Make sure you've copied the font to android/app/src/main/assets/fonts.
  • Delete the android/app/build folder.
  • Recompile the project.

Red screen with "Unrecognized font family" error on iOS

  • Make sure you've added manually the reference of your .ttf on your xcodeproj Resources folder.
  • Check that the font you are trying to use appears in Info.plist, if you've added the whole folder and it's blue in color, then you need to add it to the path.
  • Check that the font is copied in the Copy Bundle Resources in Build Phases.
  • Recompile the project.

Android build fails on Windows for no good reason

npm 和 android 文件层次结构往往会变得非常深,当您将它们组合时甚至更糟。 由于 Windows 文件系统具有最大长度,长文件名地址将导致许多错误,包括 Execution failed for task ':react-native-vector-icons:processReleaseResources'。 因此,尽量使项目文件夹的路径尽可能短。

License

此项目已根据 MIT 许可证 获得许可。

任何捆绑字体的版权归其各自作者所有,并且主要受 MIT 或 SIL OFL 保护。

Vector Icons for React Native

Travis npm npm Issue Stats

Perfect for buttons, logos and nav/tab bars. Easy to extend, style and integrate into your project.

Bundled Icon Sets

Browse all.

Installation

  1. Run: $ npm install react-native-vector-icons --save
  2. For each platform (iOS/Android/Windows) you plan to use, follow one of the options for the corresponding platform.

iOS

Option: Manually

If you want to use any of the bundled icons, you need to add the icon fonts to your Xcode project. Just follow these steps:

  • Browse to node_modules/react-native-vector-icons and drag the folder Fonts (or just the ones you want) to your project in Xcode. Make sure your app is checked under "Add to targets" and that "Create groups" is checked if you add the whole folder.
  • Edit Info.plist and add a property called Fonts provided by application (or UIAppFonts if Xcode won't autocomplete/not using Xcode) and type in the files you just added. It will look something like this:

XCode screenshot

Note: you need to recompile your project after adding new fonts, also ensure that they also appear under Copy Bundle Resources in Build Phases.

If you want to use the TabBar/NavigatorIOS integration or use getImageSource, then you need to add RNVectorIcons.xcodeproj to Libraries and add libRNVectorIcons.a to Link Binary With Libraries under Build Phases. More info and screenshots about how to do this is available in the React Native documentation.

Option: With CocoaPods

Add the following to your Podfile and run pod update:

pod 'RNVectorIcons', :path => 'node_modules/react-native-vector-icons'

Edit Info.plist as described above.

If you are using use_frameworks! in your Podfile you instead need to dynamically load the icon font by doing Icon.loadFont() when boostrapping your application.

Option: With rnpm

$ react-native link

Note: Some users are having trouble using this method, try one of the others if you are too.

Android

Option: With Gradle (recommended)

This method has the advantage of fonts being copied from this module at build time so that the fonts and JS are always in sync, making upgrades painless.

Edit android/app/build.gradle ( NOT android/build.gradle ) and add the following:

apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

To customize the files being copied, add the following instead:

project.ext.vectoricons = [
    iconFontNames: [ 'MaterialIcons.ttf', 'EvilIcons.ttf' ] // Name of the font files you want to copy
]

apply from: "../../node_modules/react-native-vector-icons/fonts.gradle"

Option: Manually

  • Copy the contents in the Fonts folder to android/app/src/main/assets/fonts (note lowercase font folder).
Integrating library for getImageSource and ToolbarAndroid support

These steps are optional and only needed if you want to use the Icon.getImageSource function or using custom icons in the Icon.ToolbarAndroid component.

  • Edit android/settings.gradle to look like this (without the +):
  rootProject.name = 'MyApp'

  include ':app'

  + include ':react-native-vector-icons'
  + project(':react-native-vector-icons').projectDir = new File(rootProject.projectDir, '../node_modules/react-native-vector-icons/android')
  • Edit android/app/build.gradle (note: app folder) to look like this:
  apply plugin: 'com.android.application'

  android {
    ...
  }

  dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile "com.android.support:appcompat-v7:23.0.1"
    compile "com.facebook.react:react-native:+"  // From node_modules
  + compile project(':react-native-vector-icons')
  }
  • Edit your MainApplication.java (deep in android/app/src/main/java/...) to look like this (note two places to edit):
  package com.myapp;

  + import com.oblador.vectoricons.VectorIconsPackage;

  ....

    @Override
    protected List<ReactPackage> getPackages() {
      return Arrays.<ReactPackage>asList(
        new MainReactPackage()
  +   , new VectorIconsPackage()
      );
    }

  }

Note: If you're using React Native (Android) <= 0.17, follow this instructions

Option: With rnpm

$ react-native link

Note: Some users are having trouble using this method, try one of the others if you are too.

OSX via react-native-desktop

  • Browse to node_modules/react-native-vector-icons and drag the folder Fonts to your project in Xcode. Make sure your app is checked under "Add to targets" and that "Create folder references" is checked.
  • Edit Info.plist and add a property called Application fonts resource path (or ATSApplicationFontsPath if Xcode won't autocomplete/not using Xcode) and type Fonts as the value.

Note: you need to recompile your project after adding new fonts, also ensure that the Fonts folder also appear under Copy Bundle Resources in Build Phases.

Windows via react-native-windows

  • Open your solution in Visual Studio, right click the Assets folder in your solution, click Add Existing.
  • Browse to the node_modules\react-native-vector-icons\Fonts folder, select the required font files
  • Click the Add drop-down and select Add as Link.
  • Set Copy To Output Directory property of each font file to Copy if newer

Note: you need to recompile your project after adding new fonts.

Web (with webpack)

In your webpack configuration file, add a section to handle ttf files using url-loader (or file-loader)

{
  test: /\.ttf$/,
  loader: "url-loader", // or directly file-loader
  include: path.resolve(__dirname, "node_modules/react-native-vector-icons"),
},

Then consume those files in your JavaScript entry point to get the bundled url and inject a style tag in your page:

// Use prebuilt version of RNVI in dist folder
import Icon from 'react-native-vector-icons/dist/FontAwesome';

// Generate required css
import iconFont from 'react-native-vector-icons/Fonts/FontAwesome.ttf';
const iconFontStyles = `@font-face {
  src: url(${iconFont});
  font-family: FontAwesome;
}`;

// Create stylesheet
const style = document.createElement('style');
style.type = 'text/css';
if (style.styleSheet) {
  style.styleSheet.cssText = iconFontStyles;
} else {
  style.appendChild(document.createTextNode(iconFontStyles));
}

// Inject stylesheet
document.head.appendChild(style);

Icon Component

You can either use one of the bundled icons above or roll your own custom font.

import Icon from 'react-native-vector-icons/FontAwesome';
const myIcon = (<Icon name="rocket" size={30} color="#900" />)

Properties

Any Text property and the following:

Prop Description Default
size Size of the icon, can also be passed as fontSize in the style object. 12
name What icon to show, see Icon Explorer app or one of the links above. None
color Color of the icon. Inherited

Styling

Since Icon builds on top of the Text component, most style properties will work as expected, you might find it useful to play around with these:

  • backgroundColor
  • borderWidth
  • borderColor
  • borderRadius
  • padding
  • margin
  • color
  • fontSize

NOTE: On android Text doesn't currently support border* styles, to circumvent this simply wrap your Icon with a View.

By combining some of these you can create for example :

type star

Icon.Button Component

A convenience component for creating buttons with an icon on the left side.

import Icon from 'react-native-vector-icons/FontAwesome';
const myButton = (
  <Icon.Button name="facebook" backgroundColor="#3b5998" onPress={this.loginWithFacebook}>
    Login with Facebook
  </Icon.Button>
);

const customTextButton = (
  <Icon.Button name="facebook" backgroundColor="#3b5998">
    <Text style={{fontFamily: 'Arial', fontSize: 15}}>Login with Facebook</Text>
  </Icon.Button>
);

buttons

Properties

Any Text, TouchableHighlight or TouchableWithoutFeedback property in addition to these:

Prop Description Default
color Text and icon color, use iconStyle or nest a Text component if you need different colors. white
size Icon size. 20
iconStyle Styles applied to the icon only, good for setting margins or a different color. {marginRight: 10}
backgroundColor Background color of the button. #007AFF
borderRadius Border radius of the button, set to 0 to disable. 5
onPress A function called when the button is pressed. None

Usage as PNG image/source object

Convenient way to plug this in into other components that rely on bitmap images rather than scalable vector icons. Takes the arguments name, size and color as described above.

Icon.getImageSource('user', 20, 'red').then((source) => this.setState({ userIcon: source }));

For a complete example check out the TabBarExample project.

Usage with TabBarIOS

Simply use Icon.TabBarItemIOS instead of TabBarIOS.Item. This is an extended component that works exactly the same but with three additional properties:

Prop Description Default
iconName Name of the default icon (similar to TabBarIOS.Item icon) None
selectedIconName Name of the selected icon (similar to TabBarIOS.Item selectedIcon). iconName
iconSize Size of the icon. 30
iconColor Color of the icon. None
selectedIconColor Color of the selected icon. iconColor

For example usage see Examples/TabBarExample or the examples section below. Don't forget to import and link to this project as described above if you are going to use the TabBar integration.

Note: using iconColor and selectedIconColor requires the attribute renderAsOriginal to be set to true on Icon.TabBarItemIOS.

Usage with NavigatorIOS

Use Icon.getImageSource to get an image source object and pass it as you would with backButtonIcon, leftButtonIcon or rightButtonIcon.

Note: Since NavigatorIOS doesn't rerender with new state and the async nature of getImageSource you must not use it with initialRoute until the icon is rendered, but any view added by push should be fine. Easiest way is to simple add an if statment at the beginning of you render method like this:

  render() {
    if (!this.state.myIcon) {
      return false;
    }
    return (<NavigatorIOS ... />);
  }

Facebook writes:

Development belongs to open-source community - not used by the React Native team on their apps. A result of this is that there is currently a backlog of unresolved bugs, nobody who uses this has stepped up to take ownership for it yet.

You are probably better off with Navigator.NavigationBar or react-native-navbar.

Usage with ToolbarAndroid

Simply use Icon.ToolbarAndroid instead of React.ToolbarAndroid, this is composition of the underlying ToolbarAndroid component that works the same but any *icon property also takes *iconName:

Prop Description Default
logoName Name of the navigation logo icon (similar to ToolbarAndroid logo) None
navIconName Name of the navigation icon (similar to ToolbarAndroid navIcon) None
overflowIconName Name of the overflow icon (similar to ToolbarAndroid overflowIcon). none
actions Possible actions on the toolbar as part of the action menu, takes the additional arguments iconName, iconColor and iconSize. none
iconSize Size of the icons. 24
iconColor Color of the icons. black

For example usage see Examples/IconExplorer/index.android.jsor the examples section below. Don't forget to import and link to this project as described above if you are going to use the ToolbarAndroid integration.

Custom Fonts

createIconSet(glyphMap, fontFamily[, fontFile])

Returns your own custom font based on the glyphMap where the key is the icon name and the value is either a UTF-8 character or it's character code. fontFamily is the name of the font NOT the filename. Open the font in Font Book.app or similar to learn the name. Optionally pass the third fontFile argument for android support, it should be a path to the font file in you asset folder.

import { createIconSet } from 'react-native-vector-icons';
const glyphMap = { 'icon-name': 1234, test: '∆' };
const Icon = createIconSet(glyphMap, 'FontName');

createIconSetFromFontello(config[, fontFamily[, fontFile]])

Convenience method to create a custom font based on a fontello config file. Don't forget to import the font as described above and drop the config.json somewhere convenient in your project.

import { createIconSetFromFontello } from 'react-native-vector-icons';
import fontelloConfig from './config.json';
const Icon = createIconSetFromFontello(fontelloConfig);

createIconSetFromIcoMoon(config[, fontFamily[, fontFile]])

import { createIconSetFromIcoMoon } from 'react-native-vector-icons';
import icoMoonConfig from './config.json';
const Icon = createIconSetFromIcoMoon(icoMoonConfig);

Make sure you're using the Download option in IcoMoon, and use the .json file that's included in the .zip you've downloaded. You'll also need to import the .ttf font file into your project, following the instructions above.

iOS

You have to manually make a reference of your .ttf on your xcodeproj Resources folder.

Animation

React Native comes with an amazing animation library called Animated. To use it with an icon, simply create an animated component with this line: const AnimatedIcon = Animated.createAnimatedComponent(Icon). You can also use the higher level animation library react-native-animatable.

Examples

IconExplorer

Try the IconExplorer project in Examples/IconExplorer folder, there you can also search for any icon.

Screenshot of IconExplorer

Basic Example

import Icon from 'react-native-vector-icons/Ionicons';

function ExampleView(props) {
  return (<Icon name="ios-person" size={30} color="#4F8EF7" />);
}

TabBarIOS

Full example in TabBarExample project in Examples/TabBarExample folder.

import { View, Text, TabBarIOS } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';

function TabBarView(props) {
  return (
    <TabBarIOS>
      <Icon.TabBarItem
        title="Home"
        iconName="ios-home-outline"
        selectedIconName="ios-home"
        >
        <View style={styles.tabContent}><Text>Home Tab</Text></View>
      </Icon.TabBarItem>
    </TabBarIOS>
  );
}

ToolbarAndroid

import Icon from 'react-native-vector-icons/Ionicons';

function ToolbarView(props) {
  return (
    <Icon.ToolbarAndroid
      title="Home"
      titleColor="white"
      navIconName="md-arrow-back"
      onIconClicked={props.navigator.pop}
      actions={[
        { title: 'Settings', iconName: 'md-settings', iconSize: 30, show: 'always' },
        { title: 'Follow me on Twitter', iconName: 'logo-twitter', iconColor: "#4099FF", show: 'ifRoom' },
      ]}
      overflowIconName="md-more"
    />
  );
}

Inline Icons

import { Text } from 'react-native';
import Icon from 'react-native-vector-icons/Ionicons';

function ExampleView(props) {
  return (<Text>Lorem <Icon name="ios-book" color="#4F8EF7" /> Ipsum</Text>);
}

Community examples

Generating your own icon set from a CSS file

If you already have a icon font with associated CSS file then you can easily generate a icon set with the generate-icon script.

Example usage:

./node_modules/.bin/generate-icon path/to/styles.css --componentName=MyIcon --fontFamily=myicon > Components/MyIcon.js

Options

Any flags not listed below, like --componentName and --fontFamily, will be passed on to the template.

-p, --prefix

CSS selector prefix [default: ".icon-"]

-t, --template

Template in lodash format [default: "./template/iconSet.tpl"]

For default template please provide --componentName and --fontFamily.

-o, --output

Save output to file, defaults to STDOUT

Changelog

Troubleshooting

The icons show up as a crossed out box on Android

  • Make sure you've copied the font to android/app/src/main/assets/fonts.
  • Delete the android/app/build folder.
  • Recompile the project.

Red screen with "Unrecognized font family" error on iOS

  • Make sure you've added manually the reference of your .ttf on your xcodeproj Resources folder.
  • Check that the font you are trying to use appears in Info.plist, if you've added the whole folder and it's blue in color, then you need to add it to the path.
  • Check that the font is copied in the Copy Bundle Resources in Build Phases.
  • Recompile the project.

Android build fails on Windows for no good reason

Both npm and android file hierarchies tend to get very deep and even worse when you combine them. Since Windows file system has a max length, long file name addresses will result in numerous errors including Execution failed for task ':react-native-vector-icons:processReleaseResources'. So try to keep the path to your project folder as short as possible.

License

This project is licenced under the MIT License.

Any bundled fonts are copyright to their respective authors and mostly under MIT or SIL OFL.

更多

友情链接

    我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
    原文