在我的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
這是實現國家設置所需的綁定。