我正在尝试调用其他函数中的函数
因此,如果我这样做,它将起作用:我在这里所做的只是从我的 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/