2016-08-04 88 views
1

我有这样的功能:如何避免React组件自动绑定'this'?

obj = { 
    func: function() { 
    console.log(this); 
    } 
} 

它被传递反应成分为道具:

React.createElement(Component, { 
    funcAsProp: obj.func 
} 

然后调用在一个反应​​成分是这样的:

let Component = React.createClass({ 
    displayName: 'Component', 

    clickHandler: function() { 
    this.props.funcAsProp(); 
    }, 

    render: function() { 
    return React.createElement('div', { 
     onClick: this.clickHandler 
    }); 
    } 
}); 

当像这样调用obj.func这是组件。我仍然对Javascript'this'和React自动绑定感到困惑。上下文绑定到由React obj.func还是这是一些基本的Javascript的东西,我不明白吗?

如果是关于自动绑定,我该如何在不绑定的情况下调用该函数?

回答

1

您可以设置this传递obj.func道具之前,因为func丢失自己的上下文,并使用React的组件上下文

const obj = { 
 
    name: 'obj, name', 
 
    
 
    func: function() { 
 
    console.log(this.name); 
 
    } 
 
}; 
 

 
let Component = React.createClass({ 
 
    displayName: 'Component', 
 

 
    clickHandler: function() { 
 
    this.props.funcAsProp(); 
 
    }, 
 

 
    render: function() { 
 
    return React.createElement('div', { 
 
     onClick: this.clickHandler 
 
    }, 'Click'); 
 
    } 
 
}); 
 

 
ReactDOM.render(
 
    React.createElement(Component, { funcAsProp: obj.func.bind(obj) }), 
 
    document.getElementById('container') 
 
);
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script> 
 
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script> 
 
<div id="container"></div>

1

当你做funcAsProp: obj.func你失去了你的上下文。现在您有funcAsProp等于func并且目前没有关于obj的信息。试试这个:

React.createElement(Component, { 
    funcAsProp: obj 
} 

,并在处理程序:

this.props.funcAsProp.func(); 

,或者你可以绑定您的背景:

React.createElement(Component, { 
    funcAsProp: obj.func.bind(obj) 
} 
1

this将函数调用的上下文中,所以在这种情况下这将是Component。这是使用Javascript默认行为,如果你希望你的function绑定到你宣布的时候需要做这样的事情的原初语境:

obj = { 
    func: function() { 
    console.log(this); 
    }.bind(this); 
} 

或向下传递的功能组件时:

React.createElement(Component, { funcAsProp: obj.func.bind(this) } 
+0

这是错误的,如果你这样做,这个上下文将不是'obj',例如,如果你在浏览器中的全局范围内,它将是'window' – Maxx

+0

第一个建议设置'undefined'。我可以将它绑定到窗口或其他对象,但不能自己。 –