2016-10-27 29 views
1

方法我有一個這樣的代碼:使用函數外呈現reactjs

//my_file.js

var React = require('react'); 
var ReactDom = require('react-dom'); 
var App = React.createClass({ 
    getInitialState:function(){ 
     return {//something}; 
    }, 
    myFunction:function(html){ 
     //some code 
    }, 
    render:function(){ 
     //some code 
     var someVar1, someVar2, someVar3; 
     someVar1.map(function(i, j){ 
      someVar2.campos.map(function(k, j){ 
       someVar3.campos.map(function(z, k){ 
        this.myFunction(something); 
       } 
      } 
     } 
     return (
      <div> 
       { //something } 
      </div> 
     ); 
    } 
}); 
module.exports=App; 

my_file.js:16未捕獲的類型錯誤:this.myFunction不是一個函數。我什麼都錯了?我如何在渲染內使用該功能?

+0

這裏面的函數很可能指向窗口對象而不是你的組件對象。 –

回答

3

問題是在.mapthis指的是全局範圍而不是你的組件。有幾種方法,你可以怎麼解決這個問題

  1. 變量

    var self = this; 
    someVar1.map(function(i, j){ 
        someVar2.campos.map(function(k, j){ 
        someVar3.campos.map(function(z, k){ 
         self.myFunction(something); 
        }); 
        }) 
    }) 
    
  2. 使用箭頭功能設置this每個.map

    someVar1.map(function(i, j){ 
        someVar2.campos.map(function(k, j){ 
        someVar3.campos.map(function(z, k){ 
         this.myFunction(something); 
        }, this); 
        }, this) 
    }, this) 
    
  3. this

    someVar1.map((i, j) => { 
        someVar2.campos.map((k, j) => { 
        someVar3.campos.map((z, k) => { 
         this.myFunction(something); 
        }); 
        }) 
    }) 
    
+1

謝謝,解決方案2。 – pmirnd