javascript - React AppendChild 组件不起作用

标签 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组件也是。问题是,我附加到此 <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() 一起使用的节点? ?

或者: 是否有一种“React 方式”可以动态地将子组件附加到我的 this.steps

最佳答案

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

}

关于javascript - React AppendChild 组件不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37041520/

相关文章:

javascript - 如何使标题元素的宽度向左缓慢移动

javascript - Reactjs类型错误: Unable to get property 'string' of undefined or null reference Anonymous function

javascript - Jest 测试失败

javascript - 曲线对象警告 : zero-width box with no accountable parent IE8-7

javascript - 如何在javascript中获取从窗口顶部到特定div/标签的高度

javascript - 浏览器唯一键

reactjs - 在异步 componentDidMount 时使用 React 的 Jest 和 Enzyme 进行测试

javascript - Facebook 页面插件无法预览

Java 需要帮助来关闭 Stream

javascript - jQuery post() 和读取 cookie