【发布时间】:2022-01-04 00:56:36
【问题描述】:
在代码中,我有三个“帖子”(卡片),我想分别为三个帖子处理点赞按钮(心)。 第一个帖子(顶部卡片)的 ID 为 1,第二个帖子的 ID 为 2,第三个帖子的 ID 为 3。现在,所有三张卡片的状态都相同,我应该并且可以为每张卡片创建一个状态吗?
import { StatusBar } from 'expo-status-bar';
import { StyleSheet, View, SafeAreaView, ScrollView} from 'react-native';
import {useState} from 'react';
import Card from './components/card';
export default function App() {
const [liked, setLiked] = useState();
function onPicLike(id)
{
alert(id);
if(liked){
setLiked(false);
} else
setLiked(true);
};
return (
<SafeAreaView style={styles.container}>
<ScrollView style={styles.body}>
<Card image={require('./assets/picture1.png')} liked={liked} id={1} onLike={onPicLike}/>
<Card image={require('./assets/picture2.png')} liked={liked} id={2} onLike={onPicLike}/>
<Card image={require('./assets/picture3.png')} liked={liked} id={3} onLike={onPicLike}/>
</ScrollView>
<StatusBar style="auto" />
</SafeAreaView>
);
}
const styles = StyleSheet.create({
container: {
flex: 1,
paddingTop: Platform.OS === "android" ? 30 : StatusBar.currentHeight,
backgroundColor: '#D0CEE2'
},
body: {
flex: 1,
backgroundColor: 'lightgray'
}
});
import { StyleSheet, Text, View, SafeAreaView, Image, TouchableOpacity} from 'react-native';
import { FontAwesome } from '@expo/vector-icons';
import { TouchableWithoutFeedback } from 'react-native-web';
export default function Card({image, liked, id, onLike}) {
console.log(liked);
return (
<View style={styles.card}>
<View style={{justifyContent: 'center', alignItems: 'center'}}>
<TouchableWithoutFeedback onLongPress={() =>onLike(id)}>
<Image source={image} style={{width: 50, height: 50, resizeMode: 'contain', borderRadius: 20}}/>
</TouchableWithoutFeedback>
</View>
<View style={styles.footer}>
<Text style={[{ flex: 1}, styles.actionButtons]}>
Comment
</Text>
<Text style={[styles.actionButtons, {marginRight: 5}]}>
Like
</Text>
<TouchableOpacity onPress={() =>onLike(id)}>
<FontAwesome name="heart" size={16} color={liked ? "red" : "grey"} />
</TouchableOpacity>
</View>
</View>
);
}
const styles = StyleSheet.create({
card: {
backgroundColor: 'white',
marginHorizontal: 50,
minHeight: 100,
borderRadius: 10,
marginVertical: 30,
padding: 10,
},
footer: {
flexDirection: 'row',
alignItems: 'center',
flex: 1,
paddingTop: 10
},
actionButtons: {
fontSize: 16
}
});
【问题讨论】:
-
类似这样的东西:
<Card ... onLike={() => onPicLike(1)} />。在liked状态下,您拥有一个结构,例如一个数组,每张卡片的真/假:[false, true, false]- 喜欢第二个
标签: reactjs react-native react-hooks