2016-05-05 12 views
0

私はどこからでも探しており、これに対する解決策を見つけることができません。React AppendChildコンポーネントが動作しません

私は単純に次のことをやろうとしている:

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'. 

私は推測します私の主な質問はこれです:this.steps.appendChild()と一緒に使用できるノードにReact Componentをどのように変換できますか?

OR:子どものコンポーネントを私のthis.stepsに動的に追加する「リアクション方法」はありますか?

+0

のようになりますか? – QoP

+0

@QoPが正しい。エンドユーザーがステップと対話できるように 'this.steps'に追加されたコンポーネントを表示する必要があります – skplunkerin

答えて

3

this.stepsは配列でなければなりません。マップ関数を使用してその配列をレンダリングすることができます。

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

それはとてもあなたが「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> 
    })} 

} 
+0

あなたは王です@QoP!ありがとうございました:)私は自分のコンポーネントの中で小道具にアクセスできないという問題を抱えていましたが、私が必要としていた小道具の属性を作成するためにcloneElementを更新しました。完璧、ありがとう! – skplunkerin

関連する問題