据我所知,ES6箭头函数“在调用它们时保留this
上下文”。我在React组件中看到了使用它们在类方法中绑定它的示例。我知道我可以在这样的构造绑定:箭头函数“this”绑定在React组件中不起作用
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箭头财产,https://stackoverflow.com/a/43601993/3731501 – estus
它不concidental,这些问题共同的话题。 Dupe问题有*完全相同的问题,[原因和解决方案](https://stackoverflow.com/a/41464305/3731501)也应该是相同的。如果解决方案中提出的解决方案不适用于您,请考虑用更新的详细信息重新提问该问题。 – estus
我正在查看评论中的链接stackoverflow.com/a/43601993/3731501我后来在顶部看到链接并意识到错误。 – mhatch