获得 "cannot read property of undefined" 编写的反应组件是 ES6

getting "cannot read property of undefined" with react component written is ES6

我正在学习 React。我正在学习一个使用 ES5 的教程系列。我正在尝试用 ES6 编写我的组件,当我查看 React 的相关文档时,这似乎是一个足够简单的过程。

这是给我带来问题的代码:

import React from 'react';

import Button from './button';
import ListItem from './list-item';

export default class DropDown extends React.Component {
    constructor() {
        super();
        this.state = {open: false};
    }

    handleClick() {
        this.state.open = true;
    }

    render() {

        var list = this.props.items.map((item) => {
            return <ListItem item={item}/>
        });

        return (
            <div className="dropdown">
                <Button onClick={this.handleClick} className='btn-default' title={this.props.title}
                        subTitleClassName='caret'/>

                <ul className={'dropdown-menu ' + (this.state.open ? "show" : "") }>
                    {list}
                </ul>
            </div>
        )
    }

}

我在

得到一个 TypeError: Cannot read property 'state' of undefined

handleClick() { this.state.open = true; }

每当我单击 Chrome 中的按钮时。 谁能告诉我为什么 this 未定义,或者我做错了什么?

我应该提一下,作为我的 gulp/browserify 构建过程的一部分,我正在使用 Babelify 将其转译为 ES5。

您收到此错误的原因是因为 'this' 在 es6 中对我们来说不是自动绑定,而在 es5 createClass 中是这样。我们可以使用 bind 来解决这个问题,也可以使用箭头函数。在您的按钮元素中,尝试以下操作:

<Button 
  onClick={(e) => this.handleClick(e)} 
  className='btn-default' 
  title={this.props.title}
  subTitleClassName='caret'
/>

正如接受的答案中提到的那样,问题在于将函数绑定到组件实例。但是,由于在每次渲染时为 Button 的 prop 创建一个新函数(这在某些优化方法中可能很敏感),因此使用箭头函数的最简单方法并不总是被认为是最佳实践。因此,您可以改用 binding-in-constructor 方法:

class Foo extends Component {
  constructor(props) {
    super(props);
    this.methodName = this.methodName.bind(this);
  }
  methodName(e) {
    // handle click
  }
  render() {
    return <Button onClick={this.methodName} />;
  }
}

这样你就可以保持 render 方法,它经常被 React 调用,build-up 代码更清晰。