[英]How to access props in other functions of imported modules
假設我創建了一個具有簡單功能(如helper.js
的基本模塊
export function HelloChandu() {
//How to access navigator props from here.
}
export function HelloTester() {
HelloChandu();
}
然后,我將該模塊import * as Helper from './helper';
到我的組件中import * as Helper from './helper';
在某些元素我當時叫onpress={Helper.HelloTester.bind(this)}
因此,通過這個,現在我可以訪問this.props HelloTester
功能,但我不能訪問this.props HelloChandu
功能。
問題 :如何從helper.js模塊中的任何函數訪問this.props
? 就像有10-20個函數一樣,並且我不必傳遞參數。
謝謝
恐怕如果您想在其中一個函數中訪問this.props,則在使用它們之前,您需要顯式地傳遞this
或將所有函數綁定到當前this
。
有幾種方法可以這樣做。
function HelloChandu() { alert(this.props); } function HelloTester() { HelloChandu.apply(this); // HelloChandu.call(this); // HelloChandu.bind(this)(); // this::HelloChandu(); // Experimental! } const obj = { props: 'my props' } HelloTester.bind(obj)()
另一種方法是將所有功能包裝在另一個功能中。
function helpers() { const functions = { HelloChandu: () => { alert(this.props); }, HelloTester: () => { functions.HelloChandu(); } }; return functions; } const obj = { props: 'my props' } helpers.call(obj).HelloTester();
1.您可以將道具保留到AsyncStorage,只要需要,就可以訪問該道具。
2.或者,如果您熟悉閉包,可以這樣做:
function Helper(ps) {
function test() {
console.log(ps.sex);
}
function test2() {
console.log(ps.name);
}
return {
test: test,
test2: test2,
}
}
var obj = Helper({name: 'abc', sex: 'male'});
obj.test();
obj.test2();
那么您應該導出Helper,然后import Helper from 'Helper.js'
export function HelloChandu(_this) {
//How to access navigator props from here.
}
export function HelloTester(_this) {
HelloChandu(_this);
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.