Tengo un componente Switch personalizado que quiero usar para mis formularios en react-native. El dilema que tengo es cómo obtener de este componente de interruptor su valor de estado actual.
Tengo una versión del interruptor que funciona en este componente:
/** @format */ // BASE import React, { useState } from 'react'; import { View, Platform, TouchableNativeFeedback, TouchableOpacity, Switch, } from 'react-native'; // CONSTANTS import Styles from '../../../../constants/Styles'; // TYPE import SubtitleOne from '../../../type/SubtitleOne'; // COMPONENTS import ListItem from '../ListItem/ListItem'; export default function SingleLineWithSwitch(props) { const [isEnabled, setIsEnabled] = useState(props.value); const toggleSwitch = () => setIsEnabled(previousState => !previousState); return ( <ListItem onPress={() => toggleSwitch()}> <View style={Styles.listSingleCointainer}> <SubtitleOne style={Styles.listTitle}>{props.title}</SubtitleOne> <View style={Styles.listSwitchView}> <Switch thumbColor={props.thumbColor} trackColor={props.trackColor} style={Styles.switchControl} value={isEnabled} onValueChange={toggleSwitch} /> </View> </View> </ListItem> ); }En mi pantalla de formulario tengo esto:
<Controller control={control} render={({ field: { onChange, onBlur, value } }) => ( <SingleLineWithSwitch title='Visible' onBlur={onBlur} onChangeText={onChange} value={value} /> )} name='visible' />Debe elevar el estado isEnabled hasta su componente principal, ese es su formulario.
Esto podría verse de la siguiente manera.
export default function SingleLineWithSwitch(props) { const isEnabled = props.enabled; const setIsEnabled = props.setIsEnabled; const toggleSwitch = () => setIsEnabled(previousState => !previousState); return ( <ListItem onPress={() => toggleSwitch()}> <View style={Styles.listSingleCointainer}> <SubtitleOne style={Styles.listTitle}>{props.title}</SubtitleOne> <View style={Styles.listSwitchView}> <Switch thumbColor={props.thumbColor} trackColor={props.trackColor} style={Styles.switchControl} value={isEnabled} onValueChange={toggleSwitch} /> </View> </View> </ListItem> ); }Entonces, en su forma
const [enabled, setIsEnabled] = useState(value) <Controller control={control} render={({ field: { onChange, onBlur, value } }) => ( <SingleLineWithSwitch title='Visible' onBlur={onBlur} onChangeText={onChange} enabled={enabled} setIsEnabled={setIsEnabled} /> )} name='visible' />