React Native函数作用域(从子函数调用父函数)

React Native function scope (Call parent function from child function)

本文关键字:函数 函数调用 Native 作用域 React      更新时间:2023-09-26

我正试图让我的头围绕函数的范围。_internalFunction工作得很好,但我如何调用_externalFunction呢?

我已经尝试了self=this,然后this._externalFunction内_renderRow,也尝试了() => {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>);
}