1

私はいたるところを見てきましたが、これに対する解決策を見つけることができません。

私は単に次のことをしようとしています:

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>作成したコンポーネントの1つである必要があり、複数のコンポーネントの子を追加し、さらには複製できるようにする必要があるということです(それが私が使用している理由です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:子コンポーネントを my に動的に追加する「React 方法」はありますthis.stepsか?

4

1 に答える 1

6

this.steps は配列である必要があり、マップ関数を使用してその配列をレンダリングできます。

また、新しいステップを追加した後にコンポーネントを自動再レンダリングするために、配列を状態に保存する必要があります。

このように見えるはずです

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

}
于 2016-05-05T06:18:43.313 に答える