skp*_*rin 1 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 )
}
}
Run Code Online (Sandbox Code Playgroud)
这对我来说似乎很简单。我有
<div className="recipe-steps" ref={(ref) => this.steps = ref}></div>
Run Code Online (Sandbox Code Playgroud)
我也需要动态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 )
Run Code Online (Sandbox Code Playgroud)
当我尝试时出现以下错误this.steps.appendChild( component ):
错误:
Uncaught TypeError: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'.
Run Code Online (Sandbox Code Playgroud)
我想我的主要问题是:如何将我的 React 组件转换为可以与 一起使用的节点this.steps.appendChild()?
或者:是否有一种“反应方式”可以将子组件动态附加到我的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>
})}
}
Run Code Online (Sandbox Code Playgroud)