据我所知,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);