[英]React.js “this” is undefined in render function
我是reactjs的新手,並創建了用於測試的組件。 這是我的代碼。
class TestComponent extends React.Component {
A(){
//content here
}
B() {
//content here
}
render() {
let ts = true;
if(ts==true){
submenu_items.push(<NavItem glyph='icon-fontello-search' eventKey={3} onClick={::this.B} name={B}/>);
} else {
submenu_items.push(<NavItem glyph='icon-fontello-gauge' eventKey={4} name={application} />);
}
return (
<div>
<div className='sidebar-nav-container'>
<Nav style={{marginBottom: 0}} ref={(c) => this._nav = c}>
{submenu_items}
<NavItem glyph='icon-ikons-logout' href='#' onClick={::this.A} name='A' />
</Nav>
</div>
</div>
);
}
}
如您所見,我在component中創建了兩個函數。
我觸發了兩個handleClick事件。
一個位於return函數{::this.A}
,另一個位於return {::this.B}
外部
不幸的是,一個功能被完美地觸發了,但是卻沒有被觸發。
它顯示錯誤"TypeError: Cannot read property 'B' of undefined"
我怎樣才能解決這個問題?
我相信submenu_items.push正在破壞{this}。 它變為submenu_items而不是react組件。
您可以在該語句之前使用別名,例如:
if(ts==true)
{ var thisB = ::this.B;
submenu_items.push(<NavItem glyph='icon-fontello-search' eventKey={3} onClick={thisB} name={B}/>); }
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.