javascript - 当我从映射数组中单击相应的 TouchableOpacity 时获取键值
问题描述
我是新来的本地人,我正在实习,但没有人能真正帮助我,我已经被这个问题困扰了一段时间,我的问题是,我映射一个数组,该数组基本上会在一个带有标题的矩形中列出来自 api 的新闻、主题和日期。一切正常,但我想单击一个矩形,例如,它显示更多特定的新但我不知道是否有任何方法可以将键值存储在变量中,以便我可以获得数组的正确坐标
{this.state.noticias.map((noticias, i) => (
(this.state.noticias[i][0] && this.state.noticias[i][1] && this.state.noticias[i][2]) == "" ?
<View key={i}></View> :
<TouchableOpacity style={styles.noticiaContainer} key={i}
onPress={this.mostrarNoticia.bind(this)} >
<View style={{ borderBottomWidth: 1, borderColor: '#0e62a5', }}>
<Text style={styles.tituloNoticia}>{noticias[0]}</Text>
</View>
<Text style={styles.assuntoNoticia}>{noticias[1]}</Text>
<Text style={styles.dataNoticia}>{noticias[2]}</Text>
</TouchableOpacity>
))}
解决方案
bind 的第二个参数是传递给新函数的参数集,因此在您映射每个“noticias”的代码中,您正在使用 bind 创建一个新函数,并传入当前的 'this ' 值作为第一个参数,但不传入任何变量。
请注意我在下面对您的代码所做的修改,我已将 'noticias' 和 'i' 值作为绑定函数调用的第二个和第三个参数传入。
{this.state.noticias.map((noticias, i) => (
(this.state.noticias[i][0] && this.state.noticias[i][1] && this.state.noticias[i][2]) == "" ?
<View key={i}></View> :
<TouchableOpacity
style={styles.noticiaContainer}
key={i}
onPress={this.mostrarNoticia.bind(this, noticias, i)} >
<View style={{ borderBottomWidth: 1, borderColor: '#0e62a5', }}>
<Text style={styles.tituloNoticia}>{noticias[0]}</Text>
</View>
<Text style={styles.assuntoNoticia}>{noticias[1]}</Text>
<Text style={styles.dataNoticia}>{noticias[2]}</Text>
</TouchableOpacity>
))}
采用上述修改,我已经为“mostrarNoticia”删除了一个示例函数签名,以及对绑定的修复应该如下所示。
import React from "react";
class YourComponent extends React.Component {
mostrarNoticia (noticias, index) {
// Given you passed the values into the bind function,
// they will be accessible here.
console.log("noticias", noticias);
console.log("index", index);
}
render () {
return (
<>
{this.state.noticias.map((noticias, i) => (
(this.state.noticias[i][0] && this.state.noticias[i][1] && this.state.noticias[i][2]) == "" ?
<View key={i}></View> :
<TouchableOpacity
style={styles.noticiaContainer}
key={i}
onPress={this.mostrarNoticia.bind(this, noticias, i)} >
<View style={{ borderBottomWidth: 1, borderColor: '#0e62a5', }}>
<Text style={styles.tituloNoticia}>{noticias[0]}</Text>
</View>
<Text style={styles.assuntoNoticia}>{noticias[1]}</Text>
<Text style={styles.dataNoticia}>{noticias[2]}</Text>
</TouchableOpacity>
))}
</>
);
}
}
基本上,使用您已经在使用的绑定函数将变量传递给函数。
推荐阅读
- powershell - 完成后删除exe或文件的脚本
- python-3.x - DateTimeField.strftime() 替换原来的值
- tensorflow - Tensorflow.js 错误“tfjsconverter.loadGraphModel 不是函数”
- python - 循环在嵌套列表中为每个列表选择一项
- excel - 在引用活动日期和时间时,尝试使用条件格式在 Excel 中创建动态甘特图
- c# - 当我在 ListBox 中插入项目时,我的屏幕也会移动
- flutter - 如何处理列表视图颤动的下拉框
- powershell - Powershell在脚本内并行执行不同命令
- c - ubuntu中c程序的libxml
- c - C 语言:在代码块上安装库