简体   繁体   English

React (native) - 在 3rd 方代码/组件中注入自定义组件而不是标准组件

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

For example i have library/package which exports some component:例如,我有导出一些组件的库/包:

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

Is there any way I can use SomeComponent but instead of TextInput I somehow inject my custom MyCustomTextInput ?有什么方法可以使用SomeComponent但不是TextInput我以某种方式注入我的自定义MyCustomTextInput

I know that is possible to create SomeComponent with CustomTextInput prop (it does not matter if CustomTextInput default value is specified like this or with defaultProps static initialization):我知道可以使用CustomTextInput prop创建SomeComponent (不管是像这样指定CustomTextInput默认值还是使用defaultProps static 初始化):

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

What I need is easy way to tell to the whole application (all packages, all our modules/code) "where ever you see TextInput component use my custom MyCustomTextInputComponent ".我需要的是简单的方法告诉整个应用程序(所有包,我们所有的模块/代码)“你在哪里看到TextInput组件使用我的自定义MyCustomTextInputComponent ”。 Is this possible in react/react-native?这在 react/react-native 中可能吗?

You can make index for component export package with conditions: Look at example project: Example: https://snack.expo.io/@djalik/thrilled-donut您可以根据条件为组件导出 package 创建索引:查看示例项目:示例: https://snack.expo.io/@djalikthrilled-donut/

index.js: 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);

and import in app where you need it:并在您需要的应用程序中导入:

import {MyTextInput} from './components'

What you want to achieve (substitute react-native's TextInput with your own component across the entire app) is not possible to do.您想要实现的(在整个应用程序中用您自己的组件替换 react-native 的 TextInput)是不可能的。 You can't force library to render another component either (unless it specifically lets you pass that component as a prop).您也不能强制库渲染另一个组件(除非它特别允许您将该组件作为道具传递)。 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 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