繁体   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