2017-08-05 18 views
1

在我的React應用程序中,我有幾個函數希望能夠通過幾個類似的組件訪問......但是,我想將this綁定到共享函數,以便他們可以執行更新組件狀態等操作......但是,似乎導入函數然後嘗試以「典型」React方式綁定this不起作用。React - 將`this`綁定到導入的函數

這裏是想什麼,我要完成的例證 - 在這種情況下,點擊渲染按鈕將調用來自進口共享功能文件中的功能和更新組件狀態:

//shared_functions.js 
const sharedFunctions = { 
    testFunction =() => { 
     this.setState({functionWasRun: true}) 
    } 
} 


//MyComponent.jsx 
import React, { Component } from 'react'; 
import sharedFunctions from '../static/scripts/shared_functions.js'; 
let { testFunction } = sharedFunctions; 

class MyComponent extends Component { 
    constructor(props){ 
     super(props); 
     this.testFunction = this.testFunction.bind(this) 
     this.state = { 
      functionWasRun: false 
     } 
    } 

    render(){ 
     return(
      <div> 
       <button onClick={this.testFunction}>Click</button> 
      </div> 
     ) 
    } 
} 

試圖運行這個代碼是會返回一個錯誤,如:

Uncaught (in promise) TypeError: Cannot read property 'bind' of undefined

,我得到什麼這是所有關於...但我想知道的是:是否有可能結合this原裝進口功能?

我開始在整個應用程序中看到許多類似外觀的功能,我希望通過將它們抽象成共享腳本來簡化它們,但我不確定如何實現典型的this這是實現國家設置所需的綁定。

回答

5

下面的行是不是要結合進口testFunction而是testFunction<MyComponent>

的方法要綁定導入功能,是指它直接,如下所示:

this.testFunction = testFunction.bind(this); 
// Notice how:  ^--- there is no longer a this here 

注意:你是一個例子試圖在箭頭函數上使用綁定你不能將新的上下文綁定到箭頭函數。

如果已定義,則箭頭功能的this上下文將始終設置爲位置 。


您可以通過使用常規的函數聲明,宣佈 testFunction解決這個問題:

const sharedFunctions = { 
    function testFunction(){ 
     this.setState({functionWasRun: true}) 
    } 
} 
0
import ToastTimeout from 'toastTimout' 
ToastTimeout.bind(this)('message to popup') 

我能得到這樣的背景下與該改變了setTimeout函數的簡單服務this背景變量

對不起,對於sudo代碼

相關問題