簡體   English   中英

React Native函數作用域(從子函數調用父函數)

[英]React Native function scope (Call parent function from child function)

我正在努力使自己了解功能范圍。 _internalFunction運作良好,但是我該如何調用_externalFunction

我試過self=thisthis._externalFunction內的this._externalFunction,還嘗試了() => {this._externalFunction}但沒有用。

class sandbox extends Component {
    //some code removed for clarity

    _renderRow(item) {
      const _internalFunction = () => {
        Alert.alert('Internal');
      };
      return (<Text onPress={_internalFunction}>{item}</Text>);
    }

    _externalFunction() {
      Alert.alert('External');
    };
}

這是React Native Playground中要修飾的代碼: https : //rnplay.org/apps/5CIGvA

提前致謝! :)

在ES6中,您需要手動this綁定到實例。 這是React文檔的引文:

在聲明為ES6類的React組件中,方法遵循與常規ES6類相同的語義。 這意味着他們不會自動this綁定到實例。 您必須在構造函數中顯式使用.bind(this)

因此,您需要在構造函數中綁定函數:

constructor() {
    super();
    this._externalFunction = this._externalFunction.bind(this);
}

然后可以在組件中使用this._externalFunction

_renderRow(item) {
    return (<Text onPress={this._externalFunction}>{item}</Text>);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM