【问题标题】:React.js "this" is undefined in render functionReact.js“this”在渲染函数中未定义
【发布时间】:2017-06-27 01:20:46
【问题描述】:

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

正如您在此处看到的,我在组件中创建了两个函数。

我触发了两个 handleClick 事件。

一个在返回函数{::this.A}内部,另一个在返回函数{::this.B}外部

可惜A函数完美触发了B却没有触发。

显示错误"TypeError: Cannot read property 'B' of undefined"

我该如何解决这个问题?

【问题讨论】:

  • 你确定name={B}?你有点击类型错误吗?
  • 是的。不在乎名字。您可以将名称重置为 const 即 name="B"
  • 嗯,您使用 ES7 语法进行绑定,它应该可以正常工作,但是...您可以尝试旧的 ES5 方式:this.A.bind(this) 或 ES6 匿名函数: () => this.A() 来隔离问题?
  • 如果你使用::this.A 而不是 ::this.B
  • 如果我尝试 ::this.A 而不是 this.B 也会显示未定义的错误

标签: javascript reactjs


【解决方案1】:

我相信 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}/>); }

【讨论】:

  • 我认为原因是正确的,但不是解决方案,这会破坏推送(因为它会尝试将其推送到组件)
  • 我相信你是对的@Icepickle。在那种情况下,别名是唯一的选择吗?
  • 我认为submenu_items.push(&lt;NavItem glyph='icon-fontello-search' eventKey={3} onClick={::this.B} name={B}/&gt;); 不会创建函数上下文。它只是一个对象文字。网址:t.co/kcNg5Uypzj
  • if(ts==true){ var thisB = ::this.B; submenu_items.push(); }
猜你喜欢
  • 2020-10-31
  • 2016-06-18
  • 2019-05-29
  • 2014-08-21
  • 1970-01-01
  • 2020-07-28
  • 2019-01-13
  • 1970-01-01
  • 2022-07-22
相关资源
最近更新 更多