React组件中箭头函数的"this"绑定不起作用

3
据我所知,ES6箭头函数“在被调用时保留this上下文”。我曾看到React组件中使用它们来绑定类方法中的this。我知道我可以像这样在构造函数中绑定:

constructor(props) {
    super(props);
    this.getContent = this.getContent.bind(this);
    this.handleClick = this.handleClick.bind(this);
}

但是当我尝试使用箭头函数时

handleClick = (event) => {
    this.props.openForm();
}

我收到了以下错误信息。
Module build failed: SyntaxError: Unexpected token (18:14)

  16 |   }
  17 | 
> 18 |   handleClick = (event) => {
     |               ^
  19 |     this.props.openForm();
  20 |   }
  21 | 

为什么这个不起作用?

以下是完整的组件代码:

import React from 'react';
import Section from './Section';
import { connect } from 'react-redux';
import * as actions from '../actions/actions';

class Contact extends React.Component {

  getContent() {
    return this.props.content || {};
  }

  handleClick = (event) => {
    this.props.openForm();
  }

  render() {
    return (
      <Section heading="Contact" bg="white">

          <div className="contact">

            <h3 className="contact__heading">{ this.getContent().heading }</h3>

            <p>{ this.getContent().text }</p>

            <button className="contact__button contact__btn-dialog" 
                onClick={ this.handleClick }>
              Send a message
            </button>

          </div>

      </Section>
    );
  }
}

const mapDispatchToProps = (dispatch) => {
  return {
    openForm: () => {
      dispatch(actions.showContactForm(true));
    }
  };
};

export default connect(
  null,
  mapDispatchToProps
)(Contact);

还可以参考关于bind和arrow属性的内容,https://dev59.com/tVcP5IYBdhLWcg3w8eW5#43601993 - Estus Flask
这些问题分享同一个主题并非巧合。重复的问题有着完全相同的问题,而且原因和解决方案也应该是一样的。如果重复问题中提出的解决方案对您没有起作用,请考虑使用更新后的详细信息重新提问问题。 - Estus Flask
我看了评论中的链接stackoverflow.com/a/43601993/3731501,后来看到顶部的链接才意识到错误。 - mhatch
1个回答

1
如果您将方法声明为箭头函数,则无需在构造函数中绑定它。
在这种情况下,只需使用bind或箭头函数,不要同时使用两者。

class App extends React.Component {
  constructor() {
    super()

    this.handleClick = this.handleClick.bind(this)
  }

  handleClick() {
     console.log('with constructor')
  }
  
  handleClick2 = (event) => {
    console.log('without constructor')
  }

  render() {
    return (
      <div>
        <button onClick={this.handleClick}>With constructor</button>
        <button onClick={this.handleClick2}>Without constructor</button>
      </div>
    )
  }
}

ReactDOM.render(
  <App />,
  document.getElementById('root')
)
<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="root"></div>


我在构造函数中没有它,如果您查看OP中的完整组件。this评估为null。我收到错误“Uncaught TypeError:无法读取null的'props'属性”。 - mhatch
@mhatch 请检查我的示例代码。也许可以帮助 :) - Hemerson Carlin

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接