2016-01-06 10 views
19

Mi piacerebbe che lo stile di un pulsante nella mia app cambi quando viene premuto. Qual è il modo migliore per farlo?Cambia stile pulsante alla pressione in React Native

+0

Avete bisogno per cambiare mentre viene premuto solo, e cambiare di nuovo quando l'utente non è pressante vero? O hai bisogno di cambiarlo quando viene toccato e mantenere lo stato modificato dopo che il tocco è stato fermato? –

+0

Per tornare indietro quando l'utente non lo sta premendo. – domi91c

risposta

19

Usa TouchableHighlight.

Ecco un esempio:

enter image description here

'use strict'; 

import React, { 
    Component, 
    StyleSheet, 
    PropTypes, 
    View, 
    Text, 
    TouchableHighlight, 
} from 'react-native'; 

export default class Home extends Component { 
    constructor(props) { 
    super(props); 
    this.state = { pressStatus: false }; 
    } 
    _onHideUnderlay(){ 
    this.setState({ pressStatus: false }); 
    } 
    _onShowUnderlay(){ 
    this.setState({ pressStatus: true }); 
    } 
    render(){ 
    return (
     <View style={styles.container}> 
     <TouchableHighlight 
      activeOpacity={1} 
      style={ this.state.pressStatus ? styles.buttonPress : styles.button } 
      onHideUnderlay={this._onHideUnderlay.bind(this)} 
      onShowUnderlay={this._onShowUnderlay.bind(this)} 
     > 
      <Text style={ this.state.pressStatus ? styles.welcomePress : styles.welcome }>{this.props.text}</Text> 
     </TouchableHighlight> 
     </View> 
    ) 
    } 
} 

Home.propTypes = { 
    text: PropTypes.string.isRequired, 
}; 

const styles = StyleSheet.create({ 
    container: { 
    flex: 1, 
    justifyContent: 'center', 
    alignItems: 'center', 
    backgroundColor: '#F5FCFF', 
    }, 
    welcome: { 
    fontSize: 20, 
    textAlign: 'center', 
    margin: 10, 
    color: '#000066' 
    }, 
    welcomePress: { 
    fontSize: 20, 
    textAlign: 'center', 
    margin: 10, 
    color: '#ffffff' 
    }, 
    button: { 
    borderColor: '#000066', 
    borderWidth: 1, 
    borderRadius: 10, 
    }, 
    buttonPress: { 
    borderColor: '#000066', 
    backgroundColor: '#000066', 
    borderWidth: 1, 
    borderRadius: 10, 
    }, 
}); 
+0

Questo è veramente utile! E i metodi 'onHideUnderlay' e' onShowUnderlay' non sono in conflitto con 'onPress'. Questo mi fa un po 'confondere un po'. –

+2

Solo una nota che '' deve contenere anche un gestore 'onPress' affinché funzioni (a partire da React Native v0.34) – rnevius

+0

Non sapeva di' onHideUnderlay' e 'onShowUnderlay'! Era googling per sempre per scoprire come realizzare qualcosa di simile. Grazie! – gregblass

2

uso qualcosa di simile:

class A extends React.Component { 
    constructor(props){ 
    super(props); 
    this.state = { 
     onClicked: false 
    } 
    this.handlerButtonOnClick = this.handlerButtonOnClick.bind(this); 
    } 
    handlerButtonOnClick(){ 
    this.setState({ 
     onClicked: true 
    }); 
    } 
    render() { 
    var _style; 
    if (this.state.onClicked){ // clicked button style 
     _style = { 
      color: "red" 
     } 
    } 
    else{ // default button style 
     _style = { 
      color: "blue" 
     } 
    } 
    return (
     <div> 
      <button 
       onClick={this.handlerButtonOnClick} 
       style={_style}>Press me !</button> 
     </div> 
    ); 
    } 
} 

Se si utilizza un CSS esterno, è possibile utilizzare className al posto di proprietà di stile:

render() { 
    var _class = "button"; 
    var _class.concat(this.state.onClicked ? "-pressed" : "-normal") ; 
    return (
     <div> 
      <button 
       onClick={this.handlerButtonOnClick} 
       className={_class}>Press me !</button> 
     </div> 
    ); 
    } 

Non importa come richiederlo il tuo CSS. Tieni d'occhio il metodo "handlerButtonOnClick".

Quando lo stato cambia, il componente viene rieseguito (il metodo "render" viene richiamato di nuovo).

Buona fortuna;)

+0

react-native non ha un componente pulsante. Usa touchableHighlight, touchableNativeFeedback tra gli altri. – Nico

+0

il problema non riguarda la reazione nativa o meno ... il problema sta per capire come e quando reagire applicare gli stili sul componente. Il flusso è sempre lo stesso: handleEvent -> handler -> setState -> render. La mia risposta riguarda questo flusso, non circa la risposta nativa –

1

Questo è risposta Besart Hoxhaj s' in ES6. Quando rispondo a questo, React Native è 0,34.

import React from 'react'; 
import { 
    TouchableHighlight, 
    Text, 
    Alert, 
    StyleSheet 
} from 'react-native'; 

export default class TouchableButton extends React.Component { 
    constructor(props) { 
     super(props); 
     this.state = { 
      pressed: false 
     } 
    } 
    render() { 
     return (
    <TouchableHighlight onPress={ 
     ()=> { 
      // Alert.alert(
      //  `You clicked this button`, 
      //  'Hello World!', 
      //  [ 
      //   {text: 'Ask me later', onPress:() => console.log('Ask me later pressed')}, 
      //   {text: 'Cancel', onPress:() => console.log('Cancel Pressed'), style: 'cancel'}, 
      //   {text: 'OK', onPress:() => console.log('OK Pressed')}, 
      //  ] 
      //) 
     } 
    } style={[styles.button, this.state.pressed ? {backgroundColor: 'green'} : {}]} 
    onHideUnderlay={()=>{this.setState({pressed: false})}} 
    onShowUnderlay={()=>{this.setState({pressed: true})}}> 
     <Text>Button</Text> 
    </TouchableHighlight> 
     ); 
    } 
} 

const styles = StyleSheet.create({ 
    button: { 
     padding: 10, 
     borderColor: 'blue', 
     borderWidth: 1, 
     borderRadius: 5 
    }, 
}); 
3

Utilizzare il prop:

underlayColor 

<TouchableHighlight style={styles.btn} underlayColor={'gray'} /> 

https://facebook.github.io/react-native/docs/touchablehighlight.html

+0

'underlayColor'sarà visualizzato con una leggera opacità. E l'impostazione di 'activeOpacity' su 0 ignorerà completamente tutti gli stili applicati allo stato non premuto. –