React/React-Native如何获取多个动态生成子组件的categoryType值
父组件获取动态生成子组件状态问题
场景说明
使用React Native开发应用,实现逻辑为:每点击一次家具按钮,就会按对应计数动态生成指定数量的LuggageDetailCard组件。每个LuggageDetailCard组件内部维护categoryType状态,该状态由组件内嵌的CircleRadioButton单选组件的选中事件触发更新。
需要实现的目标:在父组件LuggageDetailInfo中获取所有动态生成的LuggageDetailCard组件对应的categoryType值。
相关代码
LuggageDetailInfo.tsx
const luggageCard = (count: number, category: string) => { const result = []; const getCategoryObject = luggageDetailTypeData.filter( el => el.category === category, ); for (let i = 0; i < count; i++) { result.push( <LuggageDetailCard key={i + 1} name={getCategoryObject[0].name} img={getCategoryObject[0].image} i={i} categoryObject={getCategoryObject[0]} />, ); } return result; };
LuggageDetailCard.tsx
export default function LuggageDetailCard({img, name, i, categoryObject}) { const [categoryType, setCategoryType] = useState(''); return ( <View> <View style={{ flexDirection: 'row', alignItems: 'center', marginVertical: 15, }}> <Image source={img} resizeMode="contain" style={{width: 60, height: 40, marginRight: 5}} /> <Text> {name} {i + 1} </Text> </View> <View style={{ flexDirection: 'row', flexWrap: 'wrap', width: '95%', overflow: 'hidden', }}> <CircleRadioButton data={categoryObject.type} onSelect={(value: string) => setCategoryType(value)} /> </View> </View> ); }
CircleRadioButton.tsx
export default function CircleRadioButton({data, onSelect}) { const [userOption, setUserOption] = useState(''); const selectHandler = (value: string) => { onSelect(value); setUserOption(value); }; return ( <View style={{flexDirection: 'row', flexWrap: 'wrap'}}> {data.map((item: itemProps) => { return ( <Pressable onPress={() => selectHandler(item.value)} key={item.id} style={[ { borderColor: userOption === item.value ? PRIMARY_COLOR : LIGHT_GRAY_FONT_COLOR, backgroundColor: userOption === item.value ? PRIMARY_COLOR : 'white', }, styles.moveBtnPressable, ]}> <Text style={{ color: userOption === item.value ? 'white' : GRAY_COLOR_TEXT, }}> {item.name} </Text> </Pressable> ); })} </View> ); }
已尝试方案及问题
编写了状态收集方法setLuggageCardType,两种实现均存在异常:
- 方案1无法正常生效,
luggageTypes始终为空数组 - 方案2可生成形如
[{"id": 0, "type": "stoneBed"}, {"id": 1, "type": "superSingle"}]的结构,但存在更新异常问题
对应实现代码如下:
const setLuggageCardType = useCallback( (type: string, i: number) => { // code 1: doesn't work - luggageTyes always [] setLuggageTypes(prev => prev.map((item, index) => (index === i ? type : item)), ); // code 2: luggageTypes like [{"id": 0, "type": "stoneBed"}, {"id": 1, "type": "superSingle"}] let newElement = {id: i, type: type}; const checkLuggageTypeElement = luggageTypes.filter(el => el.id === newElement.id).length !== 0; if (checkLuggageTypeElement) { // update existing type setLuggageTypes([ ...luggageTypes.slice(0, i), newElement, ...luggageTypes.slice(i + 1, luggageTypes.length), ]); } else { // add type setLuggageTypes(prev => [...prev, newElement]); } }, [luggageTypes], );
内容的提问来源于stack exchange,提问作者small wombat
相关产品推荐
相关产品推荐

