2016-05-05 82 views
0

我一直在尋找無處不在,無法找到解決方案。反應AppendChild組件不起作用

我只是想做到以下幾點:

import ComponentOne from '../components/component-one' 
import ComponentTwo from '../components/component-two' 

class Home extends Component { 
    constructor(props) { 
     // So I can dynamically call a Component, found no other way 
     this.components = { 
      ComponentOne: <ComponentOne />, 
      ComponentTwo: <ComponentTwo /> 
     } 
    } 

    [...code removed for brevity...] 

    _appendStep(step) { 
     var component = React.cloneElement(this.components[step]) 
     this.steps.appendChild(component) 
    } 
} 

這看起來很簡單我。我有

<div className="recipe-steps" ref={(ref) => this.steps = ref}></div> 

我需要動態地appendChild組件。問題是,我追加到這個<div>的「步驟」絕對需要成爲我創建的組件之一,需要允許我添加多個子組件,甚至重複(這就是爲什麼我使用React.cloneElement())組件。

一旦我完成了所有「步驟」後,稍後的過程將解析每一步,以確定如何運行配方。

下工作得很好,但我不需要創建一個簡單的DOM節點,我需要用我已經建立了一個組件,並追加一條

var basicElement = document.createElement('h1') 
basicElement.innerHTML = "This works, but I need a component to work too" 
this.steps.appendChild(basicElement) 

我收到以下錯誤,當我嘗試this.steps.appendChild(component)

錯誤:

Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'. 

我猜我的主要問題是:如何將我的React組件轉換爲可與this.steps.appendChild()一起使用的節點?

OR:是否有一個「反應方式」動態地將兒童組件添加到我的this.steps

+0

所以要附加一些組件爲「this.steps」,然後顯示出來? – QoP

+0

@QoP正確。需要顯示附加到'this.steps'的組件,以便最終用戶可以與步驟 – skplunkerin

回答

3

this.steps應該是一個數組,然後,您將能夠使用map函數呈現該數組。

此外,您應該將陣列存儲在您的狀態,以便在添加新步驟後自動重新渲染組件。

它應該是這樣的

constructor(props) { 
    this.state = { 
     steps: [] 
    } 
    this.components = { 
     ComponentOne: <ComponentOne />, 
     ComponentTwo: <ComponentTwo /> 
    } 
} 
_appendStep(step) { 
     let componentToAdd= this.components[step]; 
     this.setState({steps: this.state.steps.concat([componentToAdd])}) 
    } 

render(){ 
    .... 
    {this.state.steps.map(function(comp,i){ 
     return <div key={'Step' + i}>{comp}</div> 
    })} 

} 
+0

互動你是王@QoP!謝謝:)我有問題無法訪問組件中的道具,但更新我的cloneElement以創建我需要修復的道具屬性。非常好,非常感謝你! – skplunkerin