如何在 React Native 中创建跨平台图标?

如何在 React Native 中创建跨平台图标?

问题描述:

我正在构建一个注册表单,我想添加图标,但图标在不同平台上看起来应该不同,例如如果我使用 Ionicons,它应该在 ios 设备和 md-person 上显示 ios-person在安卓设备上.我如何构建这样的自定义组件,所以我只需将它导入到我的注册屏幕表单中,然后添加一个基于文本输入的图标,如姓名的人.

I am building a signup form and I want to add icons but the icon should look different on different platform for example If I use Ionicons it should show ios-person on ios device and md-person on android devices. How can I build a custom component like that so I just import it in my Signup screen form and add a icon based on text input like an person for name.

你可以根据平台确定图标,如下所示:

You could determine the icon based on the platform, like so:

import { Platform } from 'react-native';

<Ionicons
  name={Platform.select({
    ios: 'ios-person',
    android: 'md-person',
  })}
/>

如果唯一的区别是 iosmd.

If the only difference is ios and md.

<Ionicons 
  name={`${Platform.OS === "ios" ? "ios" : "md"}-person`}
/>

也许是一个可重用的组件,

A re-usable component perhaps,

const Icon = ({ name }) => (
  <Ionicons 
    name={`${Platform.OS === "ios" ? "ios" : "md"}-${name}`}
  />
)

// Usage
<Icon name="person" />

再一次,这里假设唯一不同的是 iosmd.

Once more, this assumes the only thing different is ios and md.

编辑

可以像这样根据每个平台更新namesize

Updating the name and size depending on each platform can be done like so

<Ionicons
  {
    ...Platform.select({
      ios: {
        name: 'ios-person',
        size: 25,
      },
      android: {
        name: 'md-person',
        size: 35
      }
    })
  }
/>