React AppendChild组件无法正常工作

时间:2016-05-05 02:52:39

标签: javascript dom reactjs react-dom

我一直在寻找无处可寻的解决方案。

我只想尝试以下操作:

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组件。问题是,&#34;步骤&#34;我追加到这个<div>绝对需要成为我创建的组件之一,需要允许我添加多个组件子项,甚至重复(这就是我使用的原因) React.cloneElement())组件。

一旦我完成了所有&#34;步骤&#34;附后,后面的过程将解析每个步骤,以确定如何运行配方。

以下工作正常,但我不需要创建一个简单的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:是否有&#34;反应方式&#34;动态地将子组件附加到我的this.steps

1 个答案:

答案 0 :(得分:4)

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>
    })}

}
相关问题