2017-10-10 147 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

相關問題