首页 > 解决方案 > 在本机反应中隐藏/显示组件

问题描述

我想在我 onPress 自定义组件时显示。自定义组件是一个包装在多个 and 中的组件。

我的意思是,当 onPress 的时候,当然是包裹在 .

像这样,

 import React from 'react';
 import {
   SafeAreaView,
   Text,
   FlatList,
   View,
   StyleSheet,
   StatusBar,
   Image,
   ScrollView,
   TouchableHighlight,
   TouchableOpacity,
   Button,
 } from 'react-native';

import HeartButtons from './buttons';
import Item from './items';

const App = () => {

  const renderItem = ({item}: any) => (
    <View style={{backgroundColor: colors.white}}>
     <Item title={item.title} />
     <TouchableOpacity activeOpacity={0.5} style={styles.buttonHeartStyle}>
       <Image source={heart} />
     </TouchableOpacity>
     <TouchableOpacity activeOpacity={0.5} style={styles.buttonCheckStyle}>
       <Image source={check} />
     </TouchableOpacity>
    </View>
  );

 return (
  <SafeAreaView>
  <FlatList
    data={DATA}
    renderItem={renderItem}
    keyExtractor={item => item.id}
  />
  <TouchableOpacity
    activeOpacity={0.7}
    onPress={clickHandler}
    style={styles.touchableOpacityStyle}>
  </TouchableOpacity>
</SafeAreaView>
  );
    
};
export default App;

它是代码的一部分。当我单击<Item title={item.title} />时,应该在 renderItem 函数中显示。

我应该怎么办?

我已经一个星期没吃过了。如果你能帮助我,我将不胜感激。

先感谢您。

标签: react-native

解决方案


只需将您renderItem的修改为

const renderItem = ({ item }: any) => {
  const [isActive, setActive] = useState(false);
  return (
    <View style={{ backgroundColor: colors.white }}>
      <TouchableOpacity onPress={() => setActive(!isActive)}>
        <Item title={item.title} />
      </TouchableOpacity>
      {
        isActive && 
        <>
        // Add here what you want to show
        </>
      }
    </View>
  );
};

推荐阅读