JS/Reactjs - 访问从顶级函数传递的参数

JS/Reactjs - accessing a parameter passed from top level function

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 时,我迷失在范围内。

目前,idgetInitialState(id) 的参数隐藏并变成 undefined 因为 getInitialState 被调用时没有任何参数。

所以,去掉参数,就可以使用getInitialState()pBox方法中提供的id了。

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

函数 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

....