我正在使用自定义钩子来设置RadioButtons
组件。
const useRadioButtons = (data) => {
const [options, setOptions] = useState(
data?.map((properties) => ({
...properties,
isSelected: false,
})) || []
);
const [selected, setSelected] = useState();
const setOption = useCallback((id) => {
setOptions((currentOptions) => {
return currentOptions.map((item) => {
const newItem =
item.id !== id
? { ...item, isSelected: false }
: { ...item, isSelected: !item.isEnabled };
if (item.id === id) setSelected(newItem);
return newItem;
});
});
}, []);
return { options, setOption, selected };
};
export default useRadioButtons;
组件是
const RadioButtons = ({
options,
setOption,
extraComponent,
extraInfoComponent,
}) => {
return (
<View>
{options &&
options.map(({ id, name, isSelected }) => {
return (
<View key={id} style={styles.container}>
<Text style={styles.radioText}>{name}</Text>
<TouchableOpacity
style={styles.radioCircle}
onPress={() => setOption(id)}
>
{isSelected ? <View style={styles.selectedRb} /> : null}
</TouchableOpacity>
{isSelected ? extraInfoComponent : null}
{isSelected ? extraComponent : null}
</View>
);
})}
</View>
);
};
因此,在我要使用RadioButton
组件的组件中,我使用useRadioButtons
填充单选按钮。
const UmamiMenuSide = ({ sides, isRadioButton, name }) => {
const newSides = extractProducts(sides);
const { options, setOption, selected } = useRadioButtons(newSides);
const {
options: optionPotatoes,
setOption: setPotato,
selected: potatoSelected,
} = useRadioButtons(selected?.options);
const ExtraPriceComponent =
selected && selected.extraPrice ? (
<View>
<Text>Precio extra del menú: {selected.extraPrice}</Text>
</View>
) : null;
const ExtraRadioButtons =
selected && selected.isRadioButton ? (
<RadioButtons options={optionPotatoes} setOption={setPotato} />
) : null;
return (
<View>
<Text>{name}</Text>
{isRadioButton ? (
<RadioButtons
options={options}
setOption={setOption}
extraComponent={ExtraRadioButtons}
extraInfoComponent={ExtraPriceComponent}
/>
) : null}
</View>
);
};
在这个特定的组件内部,我想在另一个Radiobutton中使用一个RadioButton。内部的单选按钮取决于父单选按钮的值选项。
const {
options: optionPotatoes,
setOption: setPotato,
selected: potatoSelected,
} = useRadioButtons(selected?.options);
我认为它应该起作用,但是当从内部组件调用useRadioButton
时,状态未设置
const [options, setOptions] = useState(
data?.map((properties) => ({
...properties,
isSelected: false,
})) || []
);
...