javascript - 在 react-native 中动态更改函数 onPress 处理程序
问题描述
有没有办法动态更改onPress
函数处理程序<FlatList>
?我有三个onPress
需要通过数组传递的函数。如何更新<TouchableOpacity>
动态传递给的函数或函数名称(请参阅下面的代码)?
我的输入数组:
const menu = [
{
"id": 1,
"route": "this.onBottonPressedHome.bind(this)",
"info": "1"
},
{
"id": 2,
"route": "this.onBottonPressedSettings.bind(this)",
"info":"2"
},
{
"id": 3,
"route": this.onBottonPressedHistory.bind(this)",
"info": "3"
}
]
我的平面列表:
<FlatList
horizontal={true}
data={menu}
keyExtractor={item => item.id.toString()}
showsHorizontalScrollIndicator={false}
renderItem={({ item, index }) => (
<TouchableOpacity
onPress={item.route}
>
<Card>
<CardItem style={{ backgroundColor: '#37BBE1'}}>
<Body>
<View style={{ paddingTop: 10, width: 135 }}>
<Text style={{ fontSize: 12, textAlign:'justify', color: '#fff' }}>
{item.info}
</Text>
</View>
</Body>
</CardItem>
</Card>
</TouchableOpacity>
当我这样做时,我收到一个错误,指出bind
未在数组中定义。我该如何解决这个问题?
更新:
我已经使用三元运算符实现了这一点,好吗?这会在性能问题上产生任何问题吗?
解决方案
如果我理解正确,您的menu
数组由具有字符串值字段的对象项组成(即没有“真正的”函数绑定)。
假设这是您必须解决的约束,您可能会考虑使用不同的方法来解决此问题,而不是onPress
在渲染时动态传递处理程序,而是在事件期间动态解析处理程序,如下所示:
render() {
/* This handler dynamically selects the action to call, based on the "item"
that the user has pressed */
const onPressItemHandler = (item) => {
switch(item.id) {
case 1: {
this.onBottonPressedHome();
break;
}
case 2: {
this.onBottonPressedSettings();
break;
}
case 3: {
this.onBottonPressedHistory();
break;
}
}
}
return <FlatList
horizontal={true}
data={menu}
keyExtractor={item => item.id.toString()}
showsHorizontalScrollIndicator={false}
renderItem={({ item, index }) => (
<TouchableOpacity
onPress={ () => onPressItemHandler(item) }>
<Card>
<CardItem style={{ backgroundColor: '#37BBE1'}}>
<Body>
<View style={{ paddingTop: 10, width: 135 }}>
<Text style={{
fontSize: 12,
textAlign:'justify',
color: '#fff' }}>
{item.info}
</Text>
</View>
</Body>
</CardItem>
</Card>
</TouchableOpacity>)} />
}
推荐阅读
- python - UnicodeDecodeError:“charmap”编解码器无法解码位置 2308 中的字节 0x90:字符映射到
- css - CSS Grid - 具有自动宽度的自动列
- vba - vba访问输入参数值错误
- python - 当两个模型同时对不同的数据进行训练时,如何将一个模型从一个模型传递到另一个模型?
- swift - 添加 UIDatePicker 非日期选项
- html - 固定背景和可滚动的文本滑块
- javascript - 如何在调用 .html() 替换内容后重新初始化我的 jQuery 调用
- c - 如何在带有指针的函数中传递多个参数?
- java - AsyncTask 替代背景图像下载?(AsyncTask ---------已弃用)
- python - Python3、Pygame Sprite.Group 更新方法参数不同