简体   繁体   English

React.js“ this”在渲染函数中未定义

[英]React.js “this” is undefined in render function

I'm new to reactjs and created component for testing. 我是reactjs的新手,并创建了用于测试的组件。 Here is my code. 这是我的代码。

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>
        );
    }
}

As you can see here I created two functions in component. 如您所见,我在component中创建了两个函数。

I triggered two handleClick events. 我触发了两个handleClick事件。

One is inside the return function {::this.A} and the other is in the outside of return {::this.B} 一个位于return函数{::this.A} ,另一个位于return {::this.B}外部

Unfortunately A function is triggered perfectly but B is not triggered. 不幸的是,一个功能被完美地触发了,但是却没有被触发。

It shows error "TypeError: Cannot read property 'B' of undefined" 它显示错误"TypeError: Cannot read property 'B' of undefined"

How can I fix this? 我怎样才能解决这个问题?

I believe submenu_items.push is clobbering {this}. 我相信submenu_items.push正在破坏{this}。 this becomes submenu_items instead of the react component. 它变为submenu_items而不是react组件。

You can alias this before that statement like: 您可以在该语句之前使用别名,例如:

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM