如何在功能组件中使用 React Native Switch?
How to use React Native Switch inside a functional component?
我正在尝试使用 react-native 提供的 Switch 组件,但它不会切换。
function settings(props) {
let {changeView, header} = props;
let rememberPin = false;
let toggleRememberPin = (value) => {
rememberPin = value;
};
return (
<View style={styles.appContainer}>
<View style={styles.appBody}>
<View style={{flex:1, flexDirection: 'row',justifyContent:'center',alignItems:'center',width: Dimensions.get('screen').width,backgroundColor: Colors.white}}>
<Text>Remember PIN:</Text>
<Switch
onValueChange={toggleRememberPin}
value={rememberPin}
ios_backgroundColor="#aeaeae"
trackColor={{true: Colors.customerGreen, false: '#aeaeae',}}/>
</View>
</View>
</View>
);
}
我在视图中渲染了 Switch,我可以触摸它,它会从 OFF 变为 ON,但突然它又回到 OFF 而没有保持 ON 状态。
怎么了?
您需要了解 React 的核心概念,尤其是组件状态的工作原理。
简而言之,正常的变量分配不会导致组件重新呈现并反映更改。这就是你要使用状态概念的时候了。
正确的做法如下:
function Settings(props) {
let {changeView, header} = props;
const [rememberPin, setRememberPin] = useState(false);
const toggleRememberPin = (value) => {
setRememberPin(value);
};
return (
<View style={styles.appContainer}>
<View style={styles.appBody}>
<View style={{flex:1, flexDirection: 'row',justifyContent:'center',alignItems:'center',width: Dimensions.get('screen').width,backgroundColor: Colors.white}}>
<Text>Remember PIN:</Text>
<Switch
onValueChange={toggleRememberPin}
value={rememberPin}
ios_backgroundColor="#aeaeae"
trackColor={{true: Colors.customerGreen, false: '#aeaeae',}}/>
</View>
</View>
</View>
);
}
我正在尝试使用 react-native 提供的 Switch 组件,但它不会切换。
function settings(props) {
let {changeView, header} = props;
let rememberPin = false;
let toggleRememberPin = (value) => {
rememberPin = value;
};
return (
<View style={styles.appContainer}>
<View style={styles.appBody}>
<View style={{flex:1, flexDirection: 'row',justifyContent:'center',alignItems:'center',width: Dimensions.get('screen').width,backgroundColor: Colors.white}}>
<Text>Remember PIN:</Text>
<Switch
onValueChange={toggleRememberPin}
value={rememberPin}
ios_backgroundColor="#aeaeae"
trackColor={{true: Colors.customerGreen, false: '#aeaeae',}}/>
</View>
</View>
</View>
);
}
我在视图中渲染了 Switch,我可以触摸它,它会从 OFF 变为 ON,但突然它又回到 OFF 而没有保持 ON 状态。
怎么了?
您需要了解 React 的核心概念,尤其是组件状态的工作原理。
简而言之,正常的变量分配不会导致组件重新呈现并反映更改。这就是你要使用状态概念的时候了。
正确的做法如下:
function Settings(props) {
let {changeView, header} = props;
const [rememberPin, setRememberPin] = useState(false);
const toggleRememberPin = (value) => {
setRememberPin(value);
};
return (
<View style={styles.appContainer}>
<View style={styles.appBody}>
<View style={{flex:1, flexDirection: 'row',justifyContent:'center',alignItems:'center',width: Dimensions.get('screen').width,backgroundColor: Colors.white}}>
<Text>Remember PIN:</Text>
<Switch
onValueChange={toggleRememberPin}
value={rememberPin}
ios_backgroundColor="#aeaeae"
trackColor={{true: Colors.customerGreen, false: '#aeaeae',}}/>
</View>
</View>
</View>
);
}