2017-02-17 7 views
0

React.Children.mapから文字列変数に変更しようとすると、そのノードの色を動的に変更して、色を変更して動的に色を変更します。私は私のホームページにタイトルを持っています。私はタイトル文字列内の各文字のノードの色を更新したい。このようにそれをやろうとしているが、誤差エン取得:Cannot read property 'colorString' of undefinedReactJsでは、文字列変数

const LetterStyle = React.createClass({ 
    colorString: function(value){ 
    this.setState({color: "green"}); 
    }, 

    render: function(){ 
    const colorArray = [] 
    var childrentWithProps = React.Children.forEach(this.props.children, (child, i) => { 
     for (var i=0; i<child.length; i++){ 
     return React.Children.map(child[i], function(content, i) { 
      if(content !== " "){ 
      React.cloneElement(content, { colorString: this.colorString }) 
      } 
     }); 
     } 
    }) 

    return(
     <h1 className="lead" ref="lead"> 
     <span>{childrentWithProps}</span> 
     </h1> 
    ); 
    } 

}); 

答えて

0

あなたがvar that = thisを定義するようにしてくださいラインにReact.cloneElement(content, { colorString: this.colorString })

を得るまでにthis参照を失っているように見えます。右render function() {

render: function() 
    { 
     var that = this; 
     const colorArray = [] to preserve the properties of `this`. 

のような。また React.cloneElement(content, { colorString: that.colorString })

に行を変更した後、私はletvar、とconstの違いを読んでお勧めします。 ES6の構文では、通常varは不要で、constletと混同すると混乱することがあります。ここでの違いについて詳しく読む:

What's the difference between using "let" and "var" to declare a variable?

0

これは私がReact Top-Level APIから.MAPとはforEachの実装を見てきたの初めてです。彼らは彼らのネイティブJavaScriptの従兄弟とは使い方が異なります。

コードにはいくつかの問題があります。

あなたのエラーが発生する第一の問題:

後者の状態のためのドキュメントReact.Children.mapReact.Children.forEachは、最初は子供のキー付きの断片または配列であることと、第二は、そのコールバックされ、二つの引数を取ることonly引数は、これがReact.Children.forEachReact.Children.mapコール内で設定される値です。彼らの署名は以下の通りです:

React.Children.forEach(children, function[(thisArg)]) 

React.Children.map(children, function[(thisArg)]) 

解決策は、あなたのエラーを取り除くために、引数に渡されるのではなく、いずれかの呼び出しに渡されます。例として

、あなたの結果.mapコールは次のようになります。あなたはどの効果的でしょう、ここでのforEachを使用していた

return React.Children.map(child[i], function(this){ 
    if (content !== " "){ 
    React.cloneElement(content, { colorString: this.colorString }); 
    } 
}); 

言及する価値が第二の問題配列this.props.childrenを反復処理します。

childを超える現在の値を参照し、その要素のforループを実行して、.map呼び出しを取得しています。

childは、ループバックされる配列ではなく、単一のコンポーネントまたはReact要素を表す可能性が最も高いため、ここではアプリケーションの外観が正しくありません。

ソリューション:ここでは、forループまたはのforEachを使用しますが、両方ではない