You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

从Expo-Linking迁移至原生React Native实现深度链接及外部响应处理

从 Expo Linking 迁移到原生 React Native Linking 完整方案

一、代码层替换

原生 React Native 自带的 Linking API 和 Expo Linking 大部分兼容,但存在几处关键差异,直接修改现有代码即可适配:

  1. 替换导入语句
    将 Expo Linking 的导入替换为 RN 原生 Linking:

    // 替换前
    import * as Linking from 'expo-linking'
    // 替换后
    import { Linking } from 'react-native'
    
  2. 替代 createURL 方法
    原生 RN 没有内置 createURL,需自己实现自定义 Scheme 的链接生成逻辑:

    // 自定义链接生成工具,替换你的App Scheme(比如myapp)
    const createURL = (path) => {
      const APP_SCHEME = 'myapp';
      return `${APP_SCHEME}://${path}`;
    };
    // 原Expo代码替换为自定义方法
    const onConnectRedirectLink = createURL('onConnect')
    
  3. 调整事件监听逻辑
    原生 RN 的 Linking.addListener 返回订阅对象,需用该对象的 remove() 方法清理监听,替代 Expo 的 removeEventListener:

    useEffect(() => {
        // 获取启动时的初始链接
        const getInitialUrl = async () => {
            const initialUrl = await Linking.getInitialURL()
            if (initialUrl) setDeepLink(initialUrl)
        }
        getInitialUrl()
    
        // 监听后续的链接跳转
        const subscription = Linking.addListener('url', ({ url }) => {
            setDeepLink(url)
        })
    
        // 组件卸载时清理订阅
        return () => subscription.remove()
    }, [])
    
  4. 其余代码兼容
    原有的 openURL 调用、链接解析逻辑无需修改,可直接复用。

二、原生项目配置(关键步骤)

Expo 会自动配置 Deep Link 相关原生设置,迁移到原生 RN 需手动完成以下配置:

iOS 配置(Xcode)

  1. 打开项目目录下的 ios/[你的项目名]/Info.plist,右键选择「Open As」→「Source Code」
  2. 在 <dict> 标签内添加 URL Scheme 配置:
    <key>CFBundleURLTypes</key>
    <array>
        <dict>
            <key>CFBundleURLSchemes</key>
            <array>
                <string>myapp</string> <!-- 替换为你自定义的Scheme,和createURL里的一致 -->
            </array>
        </dict>
    </array>
    

Android 配置(AndroidManifest.xml)

  1. 打开 android/app/src/main/AndroidManifest.xml
  2. 在主 <activity> 标签内添加 Intent Filter:
    <activity
        android:name=".MainActivity"
        ...>
        <!-- 原有代码保留 -->
        <intent-filter>
            <action android:name="android.intent.action.VIEW" />
            <category android:name="android.intent.category.DEFAULT" />
            <category android:name="android.intent.category.BROWSABLE" />
            <!-- 替换为你的自定义Scheme -->
            <data android:scheme="myapp" />
        </intent-filter>
    </activity>
    

三、测试验证

修改完成后,可通过以下方式测试 Deep Link:

  • iOS 模拟器:终端执行 xcrun simctl openurl booted myapp://onConnect
  • Android 模拟器/真机:终端执行 adb shell am start -W -a android.intent.action.VIEW -d "myapp://onConnect" com.你的包名

完整迁移后代码示例

import React, { useEffect, useState } from 'react'
import { Button, View, Text } from 'react-native'
import { Linking } from 'react-native'

// 自定义链接生成工具
const createURL = (path) => {
  const APP_SCHEME = 'myapp';
  return `${APP_SCHEME}://${path}`;
};

const onConnectRedirectLink = createURL('onConnect')

export default function App() {
    const [deepLink, setDeepLink] = useState('')

    useEffect(() => {
        const getInitialUrl = async () => {
            const initialUrl = await Linking.getInitialURL()
            if (initialUrl) setDeepLink(initialUrl)
        }
        getInitialUrl()

        const subscription = Linking.addListener('url', ({ url }) => {
            setDeepLink(url)
        })

        return () => subscription.remove()
    }, [])

    useEffect(() => {
        if (!deepLink) return

        const url = new URL(deepLink)
        if (/onConnect/.test(url.pathname)) {
            // 处理onConnect逻辑
            console.log('触发onConnect链接:', url)
        }
    }, [deepLink])

    const connect = async () => {
        // 示例:打开外部链接或自定义Scheme链接
        await Linking.openURL(onConnectRedirectLink)
    }

    return (
        <View style={{ flex: 1, backgroundColor: '#333', justifyContent: 'center', alignItems: 'center' }}>
            <View style={{ paddingVertical: 20 }}>
                <Button title='Connect' onPress={connect} />
            </View>
            {deepLink && (
                <Text style={{ color: 'white', marginTop: 20, paddingHorizontal: 20 }}>
                    收到Deep Link: {deepLink}
                </Text>
            )}
        </View>
    )
}

内容的提问来源于stack exchange,提问作者Lê Văn Thành

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.17 16:35:14