【问题标题】:Arrow function "this" binding not working in React component [duplicate]箭头函数“this”绑定在 React 组件中不起作用 [重复]
【发布时间】:2018-03-22 08:11:00
【问题描述】:

据我了解,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);

【问题讨论】:

  • 另见绑定 vs 箭头属性,stackoverflow.com/a/43601993/3731501
  • 这些问题共享一个主题并非偶然。 Dupe question 完全有同样的问题,the cause and the solution 也应该是一样的。如果欺骗问题中建议的解决方案对您不起作用,请考虑使用更新的详细信息重新提出问题。
  • 我在看cmets stackoverflow.com/a/43601993/3731501中的链接,后来看到顶部的链接,意识到了错误。

标签: javascript reactjs ecmascript-6 arrow-functions


【解决方案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 计算结果为空。我收到错误“Uncaught TypeError: Cannot read property 'props' of null”
  • @mhatch 请检查我的示例代码。也许这有帮助:)
猜你喜欢
  • 2020-03-08
  • 2016-11-04
  • 1970-01-01
  • 2021-04-22
  • 1970-01-01
  • 2017-03-02
  • 2020-01-04
相关资源
最近更新 更多