React Native实现Tag组件单选高亮 仅选中项背景为绿色
问题根源
你当前的实现中每个Tag组件都独立维护自身的选中状态,组件之间没有状态同步逻辑,因此无法实现单选互斥效果。需要将选中状态提升到父组件App中统一管理,再通过props将选中状态和点击回调传递给子Tag组件即可。
修改后的App.js代码
import * as React from 'react'; import { Text, View, StyleSheet, ScrollView, useState } from 'react-native'; import Constants from 'expo-constants'; import Tag from './components/Tag' export default function App() { const categories = ["Tracts", "Timely Greetings", "Symbolic Codes", "Miscellaneous", "Shepherd's Rod", "Jezreel Letters", "Answerers"]; // 父组件统一维护当前选中的Tag const [selectedTag, setSelectedTag] = useState(''); // 处理Tag选中的回调函数 const handleTagSelect = (tagTitle) => { setSelectedTag(tagTitle); } return ( <View style={styles.container}> <ScrollView contentContainerStyle={styles.trim} horizontal> {/* 给每个Tag传递是否选中的状态和选中回调 */} { categories.map((value, index) => <Tag key={index} title={value} isActive={selectedTag === value} onSelect={handleTagSelect} />)} </ScrollView> </View> ); } const styles = StyleSheet.create({ container: { flex: 1, justifyContent: 'center', paddingTop: Constants.statusBarHeight, backgroundColor: '#ecf0f1', padding: 8, }, trim: { height: 50, flexGrow:1, backgroundColor: "yellow", } });
修改后的Tag组件代码
import React from "react"; import { Pressable, Text, View } from "react-native"; const Tag = (props) => { const defaultColor = "orange"; const activeColor = "green"; // 去掉内部的active状态,改用父组件传递的isActive属性 return ( <View style={{width: 80}} > {/* 点击时触发父组件传递的选中回调 */} <Pressable onPress={() => props.onSelect(props.title)}> <View style={{ borderRadius: 15, paddingHorizontal: 10, marginHorizontal: 10, backgroundColor: props.isActive ? activeColor : defaultColor }}> <Text style={{alignSelf:"center"}}>{props.title}</Text> </View> </Pressable> </View> ); }; export default Tag;
内容的提问来源于stack exchange,提问作者Oliver Saintilien
相关产品推荐
相关产品推荐

