2016-05-15 7 views
2

小道具としてのメソッドをすべての子に渡そうとしています。しかし、コンソールに子小道具を印刷すると、未定義と表示されます。すべての子に小道具としてのメソッドを渡す

コンソール出力:すべての子供たちに小道具としてopenLightbox、closeLightboxとsetLightboxStateメソッドを渡す

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

。変数childPropsに設定します。何の方法openLightboxがない

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

thisグローバルスコープを指し、(あなたがstrict modeを使用する場合、ブラウザでは、windowまたはundefinedである)、closeLightboxなどあなたは第二引数を通じて.mapため

this.props.children.map(function(child, i) { 
    ... 
}, this); 
___^^^^_ 
thisを設定することができます
0

this.props.childrenを直接反復すべきではありませんが、Reactはthis.props.children(https://facebook.github.io/react/docs/top-level-api.html)にマッピングするためのトップレベルのAPIを持っています。あなたはthis

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

にコンポーネントのインスタンスを反応させるのにリンクするには、矢印(ES2015中=>)関数または.bind(これ)を使用する必要がありますので

そして、マップ内の関数は、thisとしてwindowまたはundefinedを持っています

関連する問題