javascript - 箭头函数 "this"绑定(bind)在 React 组件中不起作用

标签 javascript reactjs ecmascript-6 arrow-functions

<分区>

据我了解,ES6 箭头函数“在调用它们时保留 this 上下文”。我在 React 组件中看到了使用它们在类方法中绑定(bind) this 的示例。我知道我可以像这样在构造函数中绑定(bind):

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)它。

在这种情况下,直接使用 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>

关于javascript - 箭头函数 "this"绑定(bind)在 React 组件中不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46674873/

相关文章:

javascript - 如何在 sequelize 上使用实例方法

javascript - 防止 iframe 突破 HTML 5/JS

javascript - 生成 0 到 'x' 之间的唯一随机数(整数)

javascript - 使用 CasperJS 访问网页

reactjs - History.push 在获取回调中不起作用

javascript - 从子对象引用父对象

Javascript href 不正确匹配

javascript - 如何通过应用过滤器来渲染Reducer?

javascript - 防止带有未保存更改的更改页面

javascript - ES6 数组方法用于删除/检测数组中的重复对象