2016-11-22 59 views
0

我傳遞了以下功能下列組件...如何使用母函數內部反應的地圖功能

<Main css={this.props.css} select={this.selectedCSS.bind(this)} save={this.saveCSS.bind(this)} /> 

然後Main組件內部,我使用這些功能...

<h1>Select the stylesheet you wish to clean</h1> 
{ 
    this.props.css.map(function(style){ 

     if (style) { 
      return (<div className="inputWrap"><input type="radio" name="style_name" onClick={this.props.select(style)}/><span></span><a key={style}>{style}</a></div>) 
       } 
      }) 
     } 

     </div> 
     <button className="cleanBtn" onClick={this.props.save}>Clean!</button> 

請注意,在我的map函數中,我通過了this.props.select(style)。這是來自父級的功能,我正在嘗試向它傳遞一個參數。但當我這樣做,我得到一個錯誤...

Error in event handler for runtime.onMessage: TypeError: Cannot read property 'props' of undefined 

其他函數我通過作品。我已經測試過它們。實際上,代碼起作用,唯一的問題是當我嘗試在map內部傳遞函數時。這是什麼原因?我該如何解決它?

我試着添加.bind(this),但是當我這樣做時它運行在一個無限循環中。

+0

您是否曾嘗試爲'function(style){}'做'.bind(this)'? –

回答

1

的問題是,Array.prototype.map不結合this背景下,除非明確告知至。

this.props.css.map(function(style) { 
    ... 
}, this) // binding this explicitly 

OR

this.props.css.map((style) => { // arrow function 
    ... 
}) 

OR

const self = this; 
this.props.css.map((style) => { 
    ... // access 'self.props.select' 
}) 

我也看到你的代碼的另一個問題。裏面map你這樣做

if (style) { 
    return (
     <div className="inputWrap"> 
      <input type="radio" name="style_name" onClick={this.props.select(style)}/> 
      <span>something</span> 
      <a key={style}>{style}</a> 
     </div> 
    );  
} 

這裏input元素期待的功能爲其onClick,但你實際上是通過調用this.props.select(style)並通過其返回值(如果有的話,它返回的東西),以評估功能onClick。相反,您可能需要這樣做:

this.props.css.map((style) => { 
    if (style) { 
     return (
      <div className="inputWrap"> 
       <input type="radio" name="style_name" onClick={() => this.props.select(style)}/> 
       <span>something</span> 
       <a key={style}>{style}</a> 
      </div> 
     );  
    } 
}) 
1

在您的映射函數中,this不再指向反應組件。

綁定上下文手動來解決此:

{ 
    this.props.css.map((function(style) { 
     if (style) { 
      return (<div className="inputWrap"><input type="radio" name="style_name" onClick={this.props.select(style)}/><span></span><a key={style}>{style}</a></div>) 
     } 
    }).bind(this)) 
} 

或者,使用ES6箭頭功能,它保留周圍的上下文:

{ 
    this.props.css.map(style => { 
     if (style) { 
      return (<div className="inputWrap"><input type="radio" name="style_name" onClick={this.props.select(style)}/><span></span><a key={style}>{style}</a></div>) 
     } 
    }) 
} 
+0

好吧,這工作,但我還有一個問題。我的函數'select = {this.selectedCSS.bind(this,style)}'接受一個參數。我試圖通過如上所示的孩子,但我不斷收到錯誤。什麼是從孩子到父母傳遞參數的正確方法? – Bolboa

+0

@Bolboa - 我提供了一個解決方案,通過我的回答參數 –

+0

@Bolboa,我用一個解決方案更新了我的答案。 –

0

你提到傳遞調用父級函數時的參數?作爲的onClick希望函數的引用(但意識到你需要傳遞一個參數),你可以嘗試以下方法:

onClick={() => { this.props.select(style) }} 
相關問題