2017-04-25 83 views
1
Box.expandBox(id); 


var Box= (function(){ 
    return { 
    expandBox: function(id) { 
     console.log('inside expandBox: ' + id); 
     ReactDOM.render(React.createElement(this.pBox(id)), document.getElementById('activate')) 
    }, 
    pBox: function(id) {  
     console.log('inside pBox: '+ id); 
     return React.createClass({ 
      getInitialState: function(id) { 
       console.log('inside getInitialState: '+ id); 
       return { 
        person_id: id 
       } 
      }, 

     ........ 

试图状态person_id分配到正在从外部传递的id传递参数。我在pBox里面输出了数据,但是数据在React的子函数里面丢失了。我试过做var self = this任务,但无济于事。谈到JS时,我迷失了方向。JS/Reactjs - 访问来自顶级功能

+2

'getInitialState'甚至没有获得通过任何参数,因此应见好就收它是空的 – azium

回答

1

目前,idgetInitialState(id)的参数所影响,并且变为undefined,因为getInitialState被调用时没有任何参数。

因此,删除参数,您可以使用pBox方法中提供的idgetInitialState()

pBox: function(id) {  
    console.log('inside pBox: '+ id); 
    return React.createClass({ 
     getInitialState: function() { 
      console.log('inside getInitialState: '+ id); 
      return { 
       person_id: id 
      } 
     }, 
0

功能getInitialState期待用于id一个参数。如果它没有收到,那么在本地范围内仍有id,但它包含undefined。正如@Shuhei提到的那样,从函数中删除该参数或给它一个不同的名称将允许您访问更高范围的id

为了便于阅读,我建议您将React.CreateClass分隔为另一个函数。

您的新功能将是这个样子:

function foo(id){ 
    console.log('inside pBox: '+ id); 
    return React.CreateClass({...}) //Same code you had before 
} 

而且你的代码会是这个样子:

Box.expandBox(id); 


var Box= (function(){ 
    return { 
    expandBox: function(id) { 
     console.log('inside expandBox: ' + id); 
     ReactDOM.render(React.createElement(this.pBox(id)), document.getElementById('activate')) 
    }, 
    pBox: foo 

....