我到处找,找不到解决办法。
我只是想做以下事情:
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/