如何在页面失焦/跳转时重置radio-buttons-react-native组件选中值?
问题
我正在使用React Native的radio-buttons-react-native包,需要在isFocused为false或导航至其他页面时重置单选按钮的值,且因限制无法更换其他包。以下是我的组件代码及尝试用ref重置的clearData函数,请教如何解决该问题?
<RadioButtonRN data={[{ label: "Lead" }, { label: "Client" }]} selectedBtn={(e) => { setRadioValue(e.label); handleChange(e.label, "type", el.uniqueId, index); }} ref={radioBtnRef} style={{ width: 70, height: 50, flexDirection: "row", justifyContent: "center", alignItems: "center", marginTop: -15, }} box={false} circleSize={10} activeColor={fontStyle.PRIMARY_COLOR} deactiveColor="#000000" textColor="#000000" textStyle={{ fontSize: 11, textAlign: "center", fontFamily: fontStyle.FONT_FAMILY, color: fontStyle.COLOR_BLACK, fontWeight: "normal", marginLeft: 10, }} initial={1} />
我尝试使用ref,在导航至其他页面时重建对象,相关函数如下:
function clearData() { setRadioValue(''); setTodayPlanData([ { uniqueId: uuid.v4(), type: "", id: "", time: null, reason: "", }, ]); clientRef.current[0].reset(); reasonRef.current[0].reset(); }
解决方案
1. 通过initial属性结合状态控制选中状态
radio-buttons-react-native的initial属性用于指定默认选中项的索引,我们可以用状态变量替代固定值,以此实现动态重置:
首先定义状态变量:
const [radioInitialIndex, setRadioInitialIndex] = useState(1); // 初始选中第二项(索引1)
修改组件的initial属性为状态变量,并在选中时同步更新状态:
<RadioButtonRN data={[{ label: "Lead" }, { label: "Client" }]} selectedBtn={(e) => { setRadioValue(e.label); handleChange(e.label, "type", el.uniqueId, index); // 选中项变化时更新状态 setRadioInitialIndex(e.index); }} ref={radioBtnRef} initial={radioInitialIndex} // 替换固定值为状态变量 // 其余属性保持不变... style={{ width: 70, height: 50, flexDirection: "row", justifyContent: "center", alignItems: "center", marginTop: -15, }} box={false} circleSize={10} activeColor={fontStyle.PRIMARY_COLOR} deactiveColor="#000000" textColor="#000000" textStyle={{ fontSize: 11, textAlign: "center", fontFamily: fontStyle.FONT_FAMILY, color: fontStyle.COLOR_BLACK, fontWeight: "normal", marginLeft: 10, }} />
2. 在重置函数中更新状态实现单选按钮重置
修改clearData函数,添加重置radioInitialIndex的逻辑,将其设为-1即可清除选中状态:
function clearData() { setRadioValue(''); setTodayPlanData([ { uniqueId: uuid.v4(), type: "", id: "", time: null, reason: "", }, ]); clientRef.current[0].reset(); reasonRef.current[0].reset(); // 重置单选按钮为无选中状态 setRadioInitialIndex(-1); }
3. 结合页面焦点监听自动触发重置
如果使用React Navigation,可以通过useFocusEffect监听页面失焦事件,自动执行重置:
import { useFocusEffect } from '@react-navigation/native'; import { useCallback } from 'react'; useFocusEffect( useCallback(() => { // 页面聚焦时可按需恢复默认状态(可选) return () => { // 页面失焦时触发重置 clearData(); }; }, []) );
关于ref重置的说明
radio-buttons-react-native的组件ref并未内置reset方法,所以你之前尝试的radioBtnRef.current.reset()不会生效,这是方案优先选择状态控制的原因。
内容的提问来源于stack exchange,提问作者geekalex018
相关产品推荐
相关产品推荐

