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