我有一个父屏幕“筛选器”,它显示了一系列多个选项,用户可以根据自己的意愿保存和设置自己的搜索首选项。
随着选项列表的增加,我将它们保存在一个数组中,并通过迭代的子组件来呈现它。
在父程序中,我还为每个选项保留状态挂钩,因为我需要知道所有设置,以便运行正确的搜索查询。
,MY PROBLEM,,我很难从子到父引用钩子的状态和设置者。我需要在子组件中知道每个选项状态是真还是假,以进行一些CSS更改。
如果我不使用子组件,我显然可以访问钩子,而且一切都很好,但是,我最终得到了大量重复的代码,这并不是很优雅。
这是我的父母:
// My array of filter options
const filterOptions = [
{ id: "0", name: "gin" },
{ id: "1", name: "rum" },
{ id: "2", name: "vodka" },
{ id: "3", name: "brandy" },
{ id: "4", name: "whisky" },
{ id: "5", name: "champagne" }
];
// My Parent component
const CocktailSearchScreen = (props) => {
// My state hooks
const [gin, setGin] = useState(false);
const [rum, setRum] = useState(false);
const [vodka, setVodka] = useState(false);
const [whiskey, setWhiskey] = useState(false);
const [champagne, setChampagne] = useState(false);
// my callback function triggered by Child component
const filterSetter = (option) => {
switch (option) {
case "gin":
setGin(!gin);
break;
case "rum":
setRum(!rum);
break;
case "vodka":
setVodka(!vodka);
break;
case "whiskey":
setWhiskey(!whiskey);
break;
default:
Alert.alert("Option not found");
}
};
// I'me rendering my list of option using the Child component <FilterItem />
{filterOptions.map((item, index) => {
return (
<FilterItem
id={item.id}
filterName={item.name}
onItemSelection={filterSetter}
/>
);
})}
}这是我的孩子部分..。
const FilterItem = (props) => {
// parent callback function - I set the hook by passing the item name(value)
const itemHandler = async () => {
props.onItemSelection(props.filterName);
};
return (
<TouchableOpacity onPress={itemHandler} key={props.id}>
<View
style={[
styles.modalText,
props.filterName
? { backgroundColor: Colors.accentColor, borderRadius: 4 }
: null,
]}
>
<Text
style={[
styles.modalTxt,
props.filterName ? styles.selectedTextStyle : null,
]}
>
{props.filterName}
</Text>
<Icon
name={"check"}
size={20}
style={[
styles.drawerItem,
props.filterName ? styles.selectedTextStyle : null,
]}
/>
</View>
</TouchableOpacity>
);
};在这一行代码中
props.filterName ? styles.selectedTextStyle : null,我应该检查项目钩子的状态,如果为真,则分配样式styles.selectedTextStyle,而不是检查项目名称
我想我需要找到一种方法,把州和/或设置者作为道具。在一个单个状态的情况下,它会很简单,如下所示
<FilterItem {state} {setState} />但就我而言我有很多钩子。
注意:我所有的项目名都与钩子值相同,不确定这是否有帮助。即
{ id: "0", name: "gin" },
const [gin, setGin] = useState(false);发布于 2020-09-21 10:12:03
你可以以州为对象。类似于:
const [state, setState] = useState({
gin: false,
rum: false,
vodka: false,
champagne: false,
whiskey: false,
});然后可以简化filterSetter函数:
const filterSetter = (option) => {
Object.keys(state).includes(option)
? setState({ ...state, [option]: !state[option] })
: Alert.alert("Option not found");
};为了知道过滤器的状态,您可以传递一个像isFilterActive这样的支柱
<FilterItem
isFilterActive={state[item.name]}
filterName={item.name}
onItemSelection={filterSetter}
id={item.id}
/>; 在FilterItem组件上,可以这样设置适当的样式:
props.isFilterActive ? styles.selectedTextStyle : null,https://stackoverflow.com/questions/63989795
复制相似问题