[英]ReactJS how to call a component function from another function on the same file?
[英]How to call function in ReactJS in a callback within the same component?
我在組件中有一個函數,同時我正在使用DataTables按鈕觸發顯示模式。 這是代碼段:
constructor(props) {
super(props);
this.state = {
error: null,
isLoaded: false,
table_type: 'default',
date_time : null,
data: [],
header : null
};
this.toogleBtnTbl = this.props.toogleBtnTbl.bind(this);
this.showModal = this.props.showModal.bind(this);
}
我無法在數據表的按鈕內調用函數this.showModal
,因為在這種情況下, this
引用了數據表。 我的問題是如何在action
屬性中調用this.showModal
?
buttons: [
{
text: 'View in Graph',
action: function ( e, dt, node, config ) {
this.showModal();//not working undefined
}
},
您必須更改為箭頭功能
action: ( e, dt, node, config ) => {
this.showModal();
}
從未使用過DataTables,但我認為您只需要一個匿名的立即執行函數即可捕獲“ this”並將其存儲在閉包中:
buttons: [
{
text: 'View in Graph',
action: (function(component){
return function ( e, dt, node, config ) {
component.showModal();
};
})(this);
},
action被設置為一個函數,該函數立即稱為在其自己的小詞法環境中存儲“ this”,在該環境中,返回的函數將始終可以訪問它。 讓我知道這個是否奏效。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.