2016-11-17 63 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 –