javascript - 使用函数运行函数

标签 javascript reactjs react-native

我正在尝试调用其他函数中的函数

因此,如果我这样做,它将起作用:我在这里所做的只是从我的 SearchUpdater(text) 函数调用 Updater 函数,并且它起作用。

class Search2 extends React.Component {
  constructor(props) {
    super(props);

    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows(['row 1', 'row 2']),
    };
  }

Updater(text){
       var newArray = []
        newArray.push(text)
          this.setState({
            dataSource: this.state.dataSource.cloneWithRows(newArray),
          });

}


  SearchUpdater(text){


  this.Updater(text)




  }

但是,如果我想在 SearchUpdater 中运行某些功能(我想放入一些复杂的逻辑......使其变得更容易),它会说 this.updater > 未定义...

class Search2 extends React.Component {
  constructor(props) {
    super(props);

    const ds = new ListView.DataSource({rowHasChanged: (r1, r2) => r1 !== r2});
    this.state = {
      dataSource: ds.cloneWithRows(['row 1', 'row 2']),
    };
  }

Updater(text){
       var newArray = []
        newArray.push(text)
          this.setState({
            dataSource: this.state.dataSource.cloneWithRows(newArray),
          });

}


  SearchUpdater(text){

  var ComplicatedLogicFunc = function(){
      this.Updater("HEYO")

  }
  ComplicatedLogicFunc();



  }

任何帮助都会很棒.. 谢谢!

最佳答案

这是因为内部函数 (var ComplicatedLogicFunc) 中的 this 关键字未引用 Search2 实例。

对于此示例,您可以使用 Arrow functions (保留 this 的值):

var ComplicatedLogicFunc = () => {
    this.Updater("HEYO");
};

this 关键字显式绑定(bind)到函数调用上下文:

ComplicatedLogicFunc.call(this);

或者您可以简单地将本地上下文存储在另一个变量中,如下所示:

SearchUpdater(text) {
    var self = this;

    var ComplicatedLogicFunc = function(){
        self.Updater("HEYO")
    }

    ComplicatedLogicFunc();
}

您可以在此处详细了解 this 关键字在 JavaScript 中的工作原理:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this

关于javascript - 使用函数运行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39307063/

相关文章:

react-native - 我可以寻找什么来检查项目是否设置为 "managed Expo project"

javascript - 如何根据使用的语言使用CSS增加文本的空间宽度?

javascript - 通过 AJAX 发布空值

react-native - 确定是否在 React Native WebView 中运行

html - CSS - 在动态大小的框之间画线

javascript - 从 JSON 中的对象读取数据

android - 删除 Android 上的后台位置访问权限

javascript - jQuery vegas 插件对内存的影响很大

javascript - 在客户端javascript中,如何根据环境更改我的变量?

javascript - 为什么我无法运行我的 React Native 项目?