[React Native] Writing Platform-Specific Components for iOS and Android in React Native

本文介绍如何使用React Native为iOS和Android开发平台特定的组件,同时保持相同的API接口。通过两种方法实现:一是利用Platform模块判断平台类型;二是采用平台特定的文件扩展名,如.ios.js和.android.js。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Learn to write components that render differently on iOS and Android, but present the same API. First, we'll use the Platform module to change behavior based on the platform. Then, we'll use the platform-specific file extensions, .ios.js and .android.js, to render platform-specific components.

 

There are two ways to code for different platform.
 
1. Using 'Platform' from 'react-native' package.
import {Platform} from 'react-native';
...


render() {
   if(Platform.OS === 'ios') {
        let info = <Text>From ios</Text>
   } else if(Platform.OS === 'android'){
        let info = <Text>From Android</Text>
   }
}    

This way works, but really not a good approach.

 

2. Using .ios & .android as file extention:

Create two files 'info.android.js' & 'info.ios.js':

// info.ios.js

import React from 'react';
import {Text} from 'react-native';

export const PInfo = () => (
    <Text>iOS</Text>
);



// info.android.js

import React from 'react';
import {Text} from 'react-native';

export const PInfo = () => (
    <Text>Android</Text>
);

 

Then we can use those component by:

// Import the file without extension

import {PInfo} from './info';

// Use it as normal
<PInfo />

 

转载于:https://www.cnblogs.com/Answer1215/p/6399846.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值