[英]Dynamically change function onPress handler in react-native
Is there a way to dynamically change the onPress
function handler in a <FlatList>
?有没有办法动态更改
<FlatList>
的onPress
函数处理程序? I have three onPress
functions which I need passed via an array.我有三个需要通过数组传递的
onPress
函数。 How can I update the function or function name that is passed to <TouchableOpacity>
dynamically (see my code below)?如何更新动态传递给
<TouchableOpacity>
的函数或函数名称(请参阅下面的代码)?
My input array:我的输入数组:
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"
}
] ]
My FlatList:我的平面列表:
<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>
When I do this, I get a error stating that bind
is not defined in the array.当我这样做时,我收到一个错误,指出数组中未定义
bind
。 How can I solve this ?我该如何解决这个问题?
Update:更新:
I have achieved this using ternary operators, is it good ?我已经使用三元运算符实现了这一点,好吗? Will this create any problems in performance issues ?
这会在性能问题上造成任何问题吗?
If I understand correctly, your menu
array consists of object items that have string value fields (ie no "real" function bindings).如果我理解正确,您的
menu
数组由具有字符串值字段的对象项组成(即没有“真正的”函数绑定)。
Assuming this is a constraint that you have to work around, you might consider a different approach to this problem, where instead of dynamically passing the onPress
handler at render time, you instead dynamically resolve the handler during the event like so:假设这是您必须解决的约束,您可能会考虑使用不同的方法来解决此问题,而不是在渲染时动态传递
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>)} />
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.