簡體   English   中英

React (native) - 在 3rd 方代碼/組件中注入自定義組件而不是標准組件

[英]React (native) - inject custom components instead standard ones in 3rd party code/components

例如,我有導出一些組件的庫/包:

function SomeComponent() {
    ...
    return (
       <View>
          ...
          <TextInput ... />
          ...
       </View>
    );
}

有什么方法可以使用SomeComponent但不是TextInput我以某種方式注入我的自定義MyCustomTextInput

我知道可以使用CustomTextInput prop創建SomeComponent (不管是像這樣指定CustomTextInput默認值還是使用defaultProps static 初始化):

function SomeComponent({ CustomTextInput = TextInput }) {
        ...
        return (
           <View>
              ...
              <CustomTextInput ... />
              ...
           </View>
        );
}

我需要的是簡單的方法告訴整個應用程序(所有包,我們所有的模塊/代碼)“你在哪里看到TextInput組件使用我的自定義MyCustomTextInputComponent ”。 這在 react/react-native 中可能嗎?

您可以根據條件為組件導出 package 創建索引:查看示例項目:示例: https://snack.expo.io/@djalikthrilled-donut/

index.js:

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

const  MyTextInput=()=>{
   return  <TextInput value={'custom'}/>
}


const  MyTextInput2=()=>{
   return  <TextInput value={'custom2'}/>
}

let custom1 = false;
export default (custom1?MyTextInput:MyTextInput2);

並在您需要的應用程序中導入:

import {MyTextInput} from './components'

您想要實現的(在整個應用程序中用您自己的組件替換 react-native 的 TextInput)是不可能的。 您也不能強制庫渲染另一個組件(除非它特別允許您將該組件作為道具傳遞)。 Solution here would be forking this library on github, making necessary changes to support custom component prop and using github link in your package.json file

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM