react-native - 子组件更新时更改父状态
问题描述
我有一个主组件,它有两个子组件,一个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
父组件中的 。
解决方案
正如您所说,回调将是在这种情况下使用的最简单的选择。
让我们从您的父组件开始。假设你有两个状态变量会议,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)} ...
//实际情况可能会根据您的需要而有所不同。
因此,每当您的孩子发生变化时,这些变化都会反映在父母身上。
推荐阅读
- firebase - Firebase Cloud Firestore 的成本优化模式:通过集合获取文档
- javascript - 每 3-4 个字符插入空格
- css - 设置背景混合模式和背景颜色在 HTML 电子邮件中不起作用
- angular - Chrome 开发工具不会显示所有源文件。这是正常的还是错误的?
- php - WooCommerce 类别页面上的自定义页面标题和描述
- php - 什么是 php 的包含顺序?
- java - 主键的多个条目
- c++ - BOOL CDialog::OnCommand(WPARAM wParam, LPARAM lParam) 的正确宏
- ios - 为什么用图像初始化 UIImageView 对象返回 nil?
- mdx - MDX 查询以对具有特定日期范围的日期维度进行分组