据我了解,ES6箭头函数在调用时保留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);
答案 0 :(得分: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>