據我所知,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