Javascript 箭头功能“;这";绑定在React组件中不起作用
据我所知,ES6 arrow函数“在调用时保留Javascript 箭头功能“;这";绑定在React组件中不起作用,javascript,reactjs,ecmascript-6,arrow-functions,Javascript,Reactjs,Ecmascript 6,Arrow Functions,据我所知,ES6 arrow函数“在调用时保留此上下文。”我在React组件中看到过使用它们绑定类内方法的示例。我知道我可以像这样绑定构造函数: constructor(props) { super(props); this.getContent = this.getContent.bind(this); this.handleClick = this.handleClick.bind(this); } 但是当我尝试使用箭头函数时 handleClick = (even
此上下文。”我在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);
从“React”导入React;
从“./节”导入节;
从'react redux'导入{connect};
从“../actions/actions”导入*作为操作;
类Contact扩展了React.Component{
getContent(){
返回this.props.content | |{};
}
handleClick=(事件)=>{
this.props.openForm();
}
render(){
返回(
{this.getContent().heading}
{this.getContent().text}
发送消息
);
}
}
const mapDispatchToProps=(调度)=>{
返回{
openForm:()=>{
发送(actions.showContactForm(true));
}
};
};
导出默认连接(
无效的
mapDispatchToProps
)(联系);
如果将方法声明为arrow函数,则不需要在构造函数中绑定它
在这种情况下,请直接使用bind
或arrow函数,而不要同时使用两者
类应用程序扩展了React.Component{
构造函数(){
超级()
this.handleClick=this.handleClick.bind(this)
}
handleClick(){
console.log('带构造函数')
}
handleClick2=(事件)=>{
console.log('不带构造函数')
}
render(){
返回(
带构造函数
无构造器
)
}
}
ReactDOM.render(
,
document.getElementById('root'))
)
另请参见“绑定vs箭头”属性,这些问题不能共享一个主题。被骗问题有完全相同的问题,也应该是相同的。如果在DUPE问题中提出的解决方案对你不起作用,考虑重新更新问题。我在评论StAccOfFult.COM/A/4360193/731501中查看链接,然后在顶部看到链接并实现了错误。如果您查看OP中的完整组件,此
计算结果为空。我收到错误“UncaughtTypeError:无法读取null的属性'props'”@mWatch请检查我的示例代码。也许这有帮助:)