React Native - Switch
In questo capitolo, spiegheremo il Switch componente in un paio di passaggi.
Passaggio 1: crea file
Useremo il file HomeContainer componente per la logica, ma dobbiamo creare la componente presentazionale.
Creiamo ora un nuovo file: SwitchExample.js.
Passaggio 2: logica
Stiamo passando valore da state e funzioni per attivare / disattivare gli elementi su SwitchExamplecomponente. Le funzioni di commutazione verranno utilizzate per aggiornare lo stato.
App.js
import React, { Component } from 'react'
import { View } from 'react-native'
import SwitchExample from './switch_example.js'
export default class HomeContainer extends Component {
constructor() {
super();
this.state = {
switch1Value: false,
}
}
toggleSwitch1 = (value) => {
this.setState({switch1Value: value})
console.log('Switch 1 is: ' + value)
}
render() {
return (
<View>
<SwitchExample
toggleSwitch1 = {this.toggleSwitch1}
switch1Value = {this.state.switch1Value}/>
</View>
);
}
}
Passaggio 3: presentazione
Il componente Switch richiede due prop. IlonValueChangeprop attiverà le nostre funzioni di commutazione dopo che un utente preme l'interruttore. Ilvalue prop è vincolato allo stato di HomeContainer componente.
switch_example.js
import React, { Component } from 'react'
import { View, Switch, StyleSheet }
from 'react-native'
export default SwitchExample = (props) => {
return (
<View style = {styles.container}>
<Switch
onValueChange = {props.toggleSwitch1}
value = {props.switch1Value}/>
</View>
)
}
const styles = StyleSheet.create ({
container: {
flex: 1,
alignItems: 'center',
marginTop: 100
}
})
Se premiamo l'interruttore, lo stato verrà aggiornato. Puoi controllare i valori nella console.