我一直在尋找無處不在,無法找到解決方案。反應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
?
所以要附加一些組件爲「this.steps」,然後顯示出來? – QoP
@QoP正確。需要顯示附加到'this.steps'的組件,以便最終用戶可以與步驟 – skplunkerin