【问题标题】:React Native function scope (Call parent function from child function)React Native 函数作用域(从子函数调用父函数)
【发布时间】:2016-10-13 03:20:01
【问题描述】:

我试图了解函数的范围。 _internalFunction 效果很好,但是我该如何调用 _externalFunction 呢?

我在 _renderRow 中尝试了 self=thisthis._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

提前致谢! :)

【问题讨论】:

    标签: javascript listview reactjs react-native ecmascript-6


    【解决方案1】:

    在 ES6 中,您需要手动将 this 绑定到实例。这是React documentation的引述:

    在声明为 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>);
    }
    

    【讨论】:

    • 我想补充一点,你可以通过使用箭头函数来做到这一点,所以_renderRow = (item) =&gt; { return () } 这是因为词法绑定而起作用的。我发现这比在我的构造函数中手动绑定所有内容要干净一些。
    • 嗯.. 当我完全按照主要答复中的建议进行操作时,它不起作用。当我点击时没有任何反应。然而,上面评论中的内容与return (&lt;Text onPress={this._externalFunction}&gt;{item}&lt;/Text&gt;);} 完美配合,不知道我应该如何接受这个答案,因为主要的答案似乎是正确的,但对我不起作用。我很确定我是按照你写的那样做的。
    • 你可以尝试在道具上做绑定吗? {item}
    • 我可能误解了你,但这确实有效:renderRow={this._renderRow.bind(this)}。在这种情况下,我不必在构造函数中使用箭头函数或绑定。这有什么缺点吗?我很高兴它有效:)
    猜你喜欢
    • 1970-01-01
    • 2017-03-11
    • 1970-01-01
    • 2018-03-28
    • 2016-09-07
    • 1970-01-01
    • 2016-12-26
    • 2017-12-22
    • 1970-01-01
    相关资源
    最近更新 更多