我正在更新我的饮水提醒应用程序,用户可以在其中选择一种类型的饮料然后喝水。我想要做的是我有一个包含饮料的数组,并通过该数组映射以显示它们。我需要用户选择哪种饮料,她想喝。选择后,我想更改其样式以突出显示所选饮料。我已经尝试过带有 selectedDrink 状态的嵌套对象,但据我在这里读到,嵌套对象在 React 中的性能不佳。当我使用选定状态并单击其中任何一个时,所有样式都会更改。state = { selected: false selectedDrink: { Water: false, Coffee: true, Tea: false, },};drinkList = (begin, end) => { drinks = [ 'Water', 'Coffee', 'Tea', ]; drinks = drinks.slice(begin, end);return drinks.map(data => { const imageLinks = { Water: require('../assets/images/Water.png'), Coffee: require('../assets/images/Coffee.png'), Tea: require('../assets/images/Tea.png'), }; { if (data === 'Water') { image = <Image style={styles.drinkImages} source={imageLinks.Water} />; } else if (data === 'Coffee') { image = <Image style={styles.drinkImages} source={imageLinks.Coffee} />; } else if (data === 'Tea') { image = <Image style={styles.drinkImages} source={imageLinks.Tea} />; } else { image = <Image style={styles.drinkImages} source={imageLinks.Water} />; } } return ( <View style={styles.drinkContainer}> <TouchableOpacity onPress={() => { this.setState({ selected: !this.state.selected }); }} //this is where I would like to change style based on state style={[ styles.drinkButtonContainer, this.state.selected ? styles.drinkSelectedButtonContainer : null, ]} > {image} </TouchableOpacity> <Text style={styles.infoTextStyle}>{data}</Text> </View> );});};
1 回答
临摹微笑
TA贡献1982条经验 获得超2个赞
我所做的是用空字符串创建选定状态。每次单击该项目的任何人时,我都会使用饮料名称设置状态,然后将所选状态与饮料名称进行比较,如果匹配样式将应用于所选饮料
state = {
selected: '',
};
return (
<View style={styles.drinkContainer}>
// I set the state to drink name
<TouchableOpacity
onPress={() => {
this.setState({ selected: data });
}}
// Then compare drink name with selected state and apply styling
style={[
styles.drinkButtonContainer,
this.state.selected === data ? styles.drinkSelectedButtonContainer : null,
]}
>
{image}
</TouchableOpacity>
<Text style={styles.infoTextStyle}>{data}</Text>
</View>
);
添加回答
举报
0/150
提交
取消