【问题标题】:How to dynamically include a module in React Native如何在 React Native 中动态包含模块
【发布时间】:2020-04-08 12:22:36
【问题描述】:

我正在尝试动态执行动态导入 import (this.props.myImportModulePath) 但我得到了:

Error: TrasformError index.js: index.js:Invalid call at line 12: import(_this.props.myImportModulePath), js engine: hermes  

我不确定这是否是解决方法,但我想要得到的是动态获取import ToastExample from './ToastExample';

下面是我的做法。

提前谢谢大家。

import React, {Component} from 'react';
import {AppRegistry, Text} from 'react-native';

import {name as appName} from './app.json';

class HelloWorld extends Component {

    constructor(props) {
        super(props);

        this.state = {
            OtherComponent: React.lazy(() => import (this.props.myImportModulePath))
        }
    }

    render() {
        return (
            <Text>HELLO World</Text>
        );
    }
}
AppRegistry.registerComponent(appName, () => HelloWorld);  

请注意,这在我更改时有效

OtherComponent: React.lazy(() =&gt; import (this.props.myImportModulePath))

进入

OtherComponent: React.lazy(() =&gt; import ('./myImportModule')),

即直接将路径作为字符串传递'./myImportModule',而不是将其作为prop值传递this.props.myImportModulePath

提前谢谢大家。

【问题讨论】:

    标签: javascript android reactjs react-native


    【解决方案1】:

    我认为您不能动态使用 import 但您可以动态更改您正在调用的组件,语法如本文所述:React - Dynamically Import Components

    【讨论】:

      【解决方案2】:

      我想你想根据一些条件导入一些组件。我认为你可以这样做:

      componentDidMount() {
            const { path } = this.props;
            // here your path is your full, if you use relative path, you have to add 
            // prefix
            // here you can add your condition
            import(`${path}`)
            .then(module => this.setState({ module: module.default }))   
         }
      
      render() {
        const { module: Component } = this.state; 
        <View>
        {Component && <Component path='./Footer' />} 
        </View>
      }
      
      
      
      

      如果你想使用flatlist,你可以尝试使用columnWrapperStyle风格。

      【讨论】:

        猜你喜欢
        • 2019-02-26
        • 2020-04-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-12-29
        • 1970-01-01
        • 2022-10-20
        • 1970-01-01
        相关资源
        最近更新 更多