2016-05-15 58 views
2

試圖將方法作爲道具傳遞給所有的孩子。但是在控制檯上打印子道具時,它顯示爲未定義。作爲道具給所有的孩子傳遞方法

控制檯輸出:

Object {openLightbox: undefined, closeLightbox: undefined, setLightboxState: undefined, key: 0} 

傳遞openLightbox,closeLightbox和setLightboxState方法作爲道具給所有的孩子們。在變量childProps中設置它。

var Lightbox = React.createClass({ 

    getInitialState: function(){ 
     return { display: false }; 
    }, 

    componentWillMount: function(){ 
     if (this.props.data) 
      this.setState(this.props.data); 
    }, 

    openLightbox: function(){ 
     this.setState({display: true}); 
    }, 

    closeLightbox: function(){ 
     this.setState({display: false}); 
    }, 

    setLightboxState: function(obj){ 
     this.setState(obj); 
    }, 

    render: function(){ 
     var childrenWithProps = this.props.children.map(function(child, i) { 
      var childProps = { 
       openLightbox: this.openLightbox, 
       closeLightbox: this.closeLightbox, 
       setLightboxState: this.setLightboxState, 
       key: i 
      }; 
      console.log(childProps) 
      for (var j in this.state){ 
       childProps[j] = this.state[j]; 
      } 

      var childWithProps = React.cloneElement(child, childProps); 

      return childWithProps; 
     }); 

     return (
      <div> 
       {childrenWithProps} 
      </div> 
     ); 
    } 
}); 

回答

2

.mapthis是指全球範圍內(在瀏覽器,它是windowundefined如果使用strict mode)那裏有沒有方法openLightboxcloseLightbox等,您可以設置爲this通過.map第二個參數

this.props.children.map(function(child, i) { 
    ... 
}, this); 
___^^^^_ 
0

儘管您不應該直接遍歷this.props.children,但React擁有一個頂級API來映射this.props.children(https://facebook.github.io/react/docs/top-level-api.html)。

然後內部映射函數將具有windowundefinedthis,因此應使用(在ES2015 =>)箭頭功能或.bind(本)來鏈接陣營組件實例this

var childrenWithProps = React.Children.map(this.props.children, function(child) { ... }.bind(this))

相關問題