2016-11-17 41 views
0

环顾下一个我找不到答案:我如何动态地包含一个文件,基于每个说道具的改变:这里有一些sudo代码,试图做!动态地包含文件(组件)并动态注入这些组件

class Test extends React.Component { 

    constructor(props){ 
     super(props) 
     this.state = { componentIncluded: false } 

    includeFile() { 
     require(this.props.componetFileDir) // e.g. ./file/dir/comp.js 
     this.setState({ componentIncluded: true }); 

    } 

    render() { 
     return(
      <div className="card"> 
       <button onClick={this.includeFile}> Load File </button> 
       { this.state.componentIncluded && 
        <this.state.customComponent /> 
       } 
      </div> 
     ) 
    } 
} 

所以this.props.componetFileDir访问的文件目录,但我需要动态包括它,并不能真正确实需要()作为它似乎动作onClick被调用之前运行。任何帮助都会很棒。

+0

无论如何,'Button'组件将被导入,你为什么不想要做简单的导入,然后管理导入组件的行为? –

+0

我的答案能解决您的问题吗? –

+0

因为'webpack'的稳定版本不支持'System.import',所以我使用'require.resolve'工作,并且不想在一个函数中包含'system.js'。 – Kivylius

回答

1

Em,你的代码看起来有点不对。所以我为动态注入组件创建了一个单独的演示。

在不同情况下,您可以使用不同的React生命周期函数来注入组件。像componentWillReceiveProps或componentWillUpdate一样。

componentDidMount() { 
    // dynamically inject a Button component. 
    System.import('../../../components/Button') 
     .then((component) => { 
     // update the state to render the component. 
     this.setState({ 
      component: component.default, 
     }); 
     }); 
    } 

    render() { 
    let Button = null; 
    if (this.state.component !== null) { 
     Button = this.state.component; 
    } 
    return (
     <div> 
     { this.state.component !== null ? <Button>OK</Button> : false } 
     </div> 
    ); 
    } 

后您编辑您的代码,它应该是类似下面:

class Test extends React.Component { 

    constructor(props){ 
     super(props) 
     this.state = { customComponent: null } 
     this.includeFile = this.includeFile.bind(this); 
    } 

    includeFile() { 
     System.import(this.props.componetFileDir) 
     .then((component) => { 
      this.setState({ customComponent: component.default }); 
     }); 
    } 

    render() { 
     return(
      <div className="card"> 
       <button onClick={this.includeFile}> Load File </button> 
       { 
        this.state.customComponent 
       } 
      </div> 
     ) 
    } 
} 
+0

所有使得sence,但我得到'系统没有定义',系统位于哪里,我如何导入它? – Kivylius

+0

你已经提供的链接是404。你能指点我正确的方向吗?哦,顺便说一句,我使用巴贝尔。 – Kivylius

+0

对不起。我正在用我的电话打字。 https://github.com/systemjs/systemjs –