如何解决选中和取消选中组件
我必须显示三个组件(卡片),用户可以从中选择一个。我已将这三个组件放在 ScrollView
中:
...
<ScrollView horizontal={true} showsHorizontalScrollIndicator={false}>
<LocationAndPriceCard
price={'100'}
title={'Choice 3'} />
<LocationAndPriceCard
price={'200'}
title={'Choice 2'} />
<LocationAndPriceCard
price={'300'}
title={'Choice 1'}} />
</ScrollView>
...
LocationAndPriceCard
的编码方式如下:
...
function LocationAndPriceCard({ price,title }) {
const [selectedLocation,setSelectedLocation] = useState("red")
const styles = getStyles(selectedLocation);
const selected = () => {
if (selectedLocation == "red") {
setSelectedLocation("green")
} else {
setSelectedLocation("red")
}
}
return (
<TouchableOpacity style={styles.frame} onPress={selected}>
<Text style={styles.priceTxt}>RM {price}</Text>
<Text style={styles.title} numberOfLines={2}>{title}</Text>
</TouchableOpacity>
);
}
const getStyles = (borderC) => StyleSheet.create({
frame: {
borderWidth: 1,borderColor: borderC,width: 180,backgroundColor: '#fff',borderRadius: 8,margin: 5,padding: 10,},...
在上面的代码中,当 cad 选择它时,它成功地将边框颜色更改为 green
,但我可以更改所有组件的颜色。我想让它就像选择一个一样,所有其他人都应该回到 red
颜色。
解决方法
为 LocationAndPriceCard
、value
和 onPress
创建两个新道具。
使用 value
确定选择了哪张卡片,并根据该卡片更改边框颜色。
使用 onPress
函数设置状态,该状态将具有所选卡片的 title
,我们将用于确定选择了哪张卡片。
完整工作示例:Expo Snack
import React,{ useState } from 'react';
import {
Text,View,StyleSheet,ScrollView,TouchableOpacity,} from 'react-native';
import Constants from 'expo-constants';
// You can import from local files
import AssetExample from './components/AssetExample';
// or any pure javascript modules available in npm
import { Card } from 'react-native-paper';
export default function App() {
const [selected,setSelected] = useState(null);
const handleSelected = (value) => {
setSelected(value);
};
return (
<View style={styles.container}>
<ScrollView horizontal={true} showsHorizontalScrollIndicator={false}>
<LocationAndPriceCard
price={'100'}
title={'Choice 3'}
onPress={handleSelected}
value={selected}
/>
<LocationAndPriceCard
price={'200'}
title={'Choice 2'}
onPress={handleSelected}
value={selected}
/>
<LocationAndPriceCard
price={'300'}
title={'Choice 1'}
onPress={handleSelected}
value={selected}
/>
</ScrollView>
</View>
);
}
function LocationAndPriceCard({ price,title,onPress,value }) {
return (
<TouchableOpacity
style={[styles.frame,{ borderColor: value === title?"green":"red" }]}
onPress={()=>onPress(title)}>
<Text style={styles.priceTxt}>RM {price}</Text>
<Text style={styles.title} numberOfLines={2}>
{title}
</Text>
</TouchableOpacity>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,paddingTop: Constants.statusBarHeight,backgroundColor: '#ecf0f1',padding: 8,},frame: {
borderWidth: 1,width: 50,height: 50,backgroundColor: '#fff',borderRadius: 8,margin: 5,padding: 10,});
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。