繁体   English   中英

React Native-通过onPress传递字符串或变量

[英]React Native - Passing Strings or Variables via onPress

这可能不仅仅适用于React Native,但我确实想了解这里发生了什么。

采取以下5行代码。 第3行将导致该应用无法在Expo中呈现。

<Button onPress={this.filterOfficeTypePitt} title="Pitt" />
<Button onPress={this.filterOfficeTypeAtl} title="Atl" />
<Button onPress={this.filterOfficeType("pitt")} title="DOES NOT WORK" />
<Button onPress={(e) => this.filterOfficeType("pitt")} title="Pitt" />
<Button onPress={(e) => this.filterOfficeType("atl")} title="Atl" />

我有点理解每一行的情况。

第1和2行:直接调用组件中的方法。

第3行:尝试做同样的事情并传递一个值。 这会导致应用程序崩溃。 原因是超过了最大深度。

第4和5行:我认为这是一个传递anon函数的函数,突然间我可以添加一个字符串值。

一旦使用4和5,我就可以使用一种方法来过滤列表。 当我使用1和2时,我必须为每种方法都有一个独特的方法。

我只想了解它会发生什么,以及为什么恰好#3无法正常工作。 我确定我至少需要对箭头功能有更好的了解。

包括辅助函数的代码。 它基本上从索引数组中获取数据,并将其推入FlatList组件。

filterOfficeType(officetype){
  let newarray = [];
  this.state.fulldataSource.forEach((element, index) => {
    if(element.office === officetype) {
      newarray.push(element);
    }
  });
  this.setState({
    dataSource:newarray,
    office:officetype
  });
}

filterOfficeTypePitt = () => {
  this.filterOfficeType("pitt");
}
filterOfficeTypeAtl = () => {
  this.filterOfficeType("atl");
}

第3行正在执行该函数,并尝试将其结果分配给onPress prop。 它永远不会到达那里(为什么?:在下面解释)

const Button = {
   onPress: this.filterOfficeType("pitt")
}

注意:函数在创建Button对象时被调用。

而其他行将功能分配给onPress属性

const Button = {
   onPress: this. filterOfficeTypePitt
}

要么

const Button = {
   onPress: (e) => {
      this.filterOfficeType("pitt")
   }
}

注意:该函数不被称为Button对象的创建,而是当有人按下该按钮时

第3行为何导致应用程序崩溃的原因是,它通过调用setState触发状态更改。 调用setState ,react将再次调用render() 但是此render()将再次执行该函数,这将调用setState并作出反应将再次调用render() ,因此超出最大深度并崩溃

箭头功能和普通功能之间的主要区别在this范围。 在箭头函数中, this引用其父对象,而在正常函数中, this引用自身。 您可以阅读有关箭头功能的更多信息

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM