2017-10-10 99 views
2

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

上绑定也可参见VS箭头财产,https://stackoverflow.com/a/43601993/3731501 – estus

+0

它不concidental,这些问题共同的话题。 Dupe问题有*完全相同的问题,[原因和解决方案](https://stackoverflow.com/a/41464305/3731501)也应该是相同的。如果解决方案中提出的解决方案不适用于您,请考虑用更新的详细信息重新提问该问题。 – estus

+0

我正在查看评论中的链接stackoverflow.com/a/43601993/3731501我后来在顶部看到链接并意识到错误。 – mhatch

回答

2

如果声明的方法,你不必将它绑定在构造Arrow功能。

在这种情况下,请直接使用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>

+0

我没有它在构造函数中,如果你会看看OP中的完整组件。 'this'评估为空。我得到错误“Uncaught TypeError:无法读取null的属性'道具' – mhatch

+0

@mhatch请检查我的示例代码。也许这有助于:) – mersocarlin

相关问题