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

标签 javascript reactjs react-native expo

这可能不仅仅适用于 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 行:我认为这是一个传递匿名函数的函数,突然允许我添加一个字符串值。

一旦我使用了 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 属性。它永远不会到达那里(为什么?:下面解释)

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并且react将再次调用render(),因此超出了最大深度并崩溃

箭头函数和普通函数的主要区别在于 this 作用域。在箭头函数中,this 引用其父对象,而在普通函数中,this 引用其自身。您可以阅读更多关于 arrow functions

关于javascript - React Native - 通过 onPress 传递字符串或变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50761809/

相关文章:

javascript - React-Native 应用程序在 iOS 上挂起,但在 Android 上运行正常

javascript - 语义用户界面 : Dynamically added dropdown menu doesn't change value in select

javascript - 循环未停止或未开始

reactjs - 当 Prop 更改时, react meteor 数据容器不会更新子级

javascript - 如何阻止子按钮触发 React 中的父链接?

ios - Shoutem 将 Prop 传递到另一个屏幕

reactjs - 如何将状态传递给 React Native 组件

javascript - 为什么函数内的变量对该函数内声明的回调函数可见?

javascript - onclick ="myFunction()"的反义词是什么?

javascript - onClick 在 React 中没有正确触发该函数