繁体   English   中英

如何在 React Native 中动态包含模块

[英]How to dynamically include a module in React Native

我正在尝试动态执行动态导入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(() => import (this.props.myImportModulePath))

进入

OtherComponent: React.lazy(() => import ('./myImportModule'))

也就是说,直接将路径作为字符串'./myImportModule'传递,而不是将其作为propthis.props.myImportModulePath

谢谢大家。

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

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

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样式。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM