首页 > 解决方案 > 子组件更新时更改父状态

问题描述

我有一个主组件,它有两个子组件,一个flat list和一个button group组件(来自 react-native-elements)。

我想flat list在用户点击其中一个button group选项时更新数据,但是,我无法真正弄清楚这一点,我尝试使用回调,但无法真正理解它们是如何工作的,而且它不起作用我。这是我的主要组成部分:

return (
  <SafeAreaView style={styles.homeContainer}>
    <View style={{flex: 1}}>
      <View style={styles.headerContainer}>
        <View
          style={{
            display: 'flex',
            flexDirection: 'row',
            justifyContent: 'space-between',
            alignItems: 'center',
          }}>
          <Text style={styles.title}>Groups</Text>
          <Avatar
            rounded
            source={{
              uri: profilePhotoURL,
            }}
          />
        </View>
        <Text style={styles.subtitle}>Find people to learn with</Text>
      </View>

      <OptionChooser /> {/** <---- this is the button group component*/}
      
      <FlatList
        data={meetings}
        renderItem={({item}) => (
          <TouchableOpacity
            style={styles.cardButton}
            onPress={() =>
              navigation.navigate('MeetingDetails', {meeting: item})
            }>
            <MeetingCard meetingModel={item} style={{flex: 1}} />
          </TouchableOpacity>
        )}
        keyExtractor={(item) => item.id!}
        showsVerticalScrollIndicator={false}
      />
    </View>

    <FloatingButton onPress={() => navigation.navigate('AddMeeting')} />
  </SafeAreaView>
);

这是我的按钮组 (OptionChooser) 组件:

  const OptionChooser = () => {
  const [selectedIndex, setSelectedIndex] = useState<number>(0);
  const buttons = ['All', 'Today', 'This week'];

  const updateIndex = (index) => {
    setSelectedIndex(index);
    console.log(index);
  };

  return (
    <View style={styles.buttonGroupContainer}>
      <ButtonGroup
        onPress={updateIndex}
        selectedIndex={selectedIndex}
        buttons={buttons}
        containerStyle={{height: 44, borderRadius: 4}}
        selectedButtonStyle={{backgroundColor: '#8BCFB0'}}
      />
    </View>
  );
};

我的目标是每当updateIndex被调用时OptionChooser,更新flat list父组件中的 。

标签: react-native

解决方案


正如您所说,回调将是在这种情况下使用的最简单的选择。

让我们从您的父组件开始。假设你有两个状态变量会议,selectedIndex

让子组件变笨并在父组件中管理状态而不是在两者中管理状态总是一个好主意。

您的父级将拥有 setSelectedIndex,它将更新父级 selectedIndex 状态。

所以你将状态和功能传递给孩子,如下所示

<OptionChooser selectedIndex={selectedIndex} setSelectedIndex={setSelectedIndex}/>

你的子组件必须是这样的

const OptionChooser = ({selectedIndex,setSelectedIndex}) => {
  const buttons = ['All', 'Today', 'This week'];
  return (
    <View style={styles.buttonGroupContainer}>
      <ButtonGroup
        onPress={setSelectedIndex}
        selectedIndex={selectedIndex}
        buttons={buttons}
        containerStyle={{height: 44, borderRadius: 4}}
        selectedButtonStyle={{backgroundColor: '#8BCFB0'}}
      />
    </View>
  );
};

在您的渲染中,您可以使用以下状态简单地过滤会议

<FlatList data={meetings.filter(x=>x.type==selectedIndex)} ...

//实际情况可能会根据您的需要而有所不同。

因此,每当您的孩子发生变化时,这些变化都会反映在父母身上。


推荐阅读