简体   繁体   中英

How to create a Button that Change Background Color onPress in react native?

How can i create a button/TouchableOpacity that change the background color of style={styles.view} ?

    <View style={styles.view}>

      {user &&
        <>
          <TouchableOpacity onPress={carregaUsuarioAnonimo}>

            <Image
              style={styles.avatar}
              source={{ uri: user.picture }} />
          </TouchableOpacity>

          <Text style={styles.nome_usuario}>{user.name}</Text>
        </>

      }



      <ScrollView style={styles.scrollview} ref={(view) => { setScrollview(view) }}>
        {
          mensagens.length > 0 && mensagens.map(item => (

            <View key={item.id} style={styles.linha_conversa}>
              <Image style={styles.avatar_conversa} source={{ uri: item.avatar }} />
              <View style={{ flexDirection: 'column', marginTop: 5 }}>
                <Text style={{ fontSize: 12, color: '#999' }}>{item.usuario}</Text>
                {typeof (item.mensagem) == "string" ?
                  <Text>{item.mensagem}</Text>
                  :
                  <Text> </Text>
                }

              </View>

            </View>




          ))
        }
      </ScrollView>


      <View style={styles.footer}>
        <TextInput
          style={styles.input_mensagem}
          onChangeText={text => setCaixaTexto(text)}
          value={caixaTexto} />

        <TouchableOpacity onPress={salvar}>
          <Ionicons style={{ margin: 3 }} name="md-send" size={32} color={'#999'} />

        </TouchableOpacity>




      </View>



    </View>)

you can make a condition inside the style, like that:

create a boolean inside your state and change it value to true when the button is clicked.

Inside your Touchable, drop the condition.

style={
this.state.buttonCliked ? styles.backgroundBlue : 
styles.backgroundGreen
}

I hope it helps you.

This is an example:-

state={isClicked:false}


checkToChangeStyle=()=>{
 this.setState({isClicked:!this.state.isClicked})
}


 return(
  <TouchableOpacity onPress={this.checkToChangeStyle} 
  style={this.state.isClicked ? styles.backGround1 : styles.backGround2}>
  <Text>Your Button</Text>
  </TouchableOpacity>
 )


const styles=StylesSheet.create({
 backGround1:{backgroundColor:'green'},
 backGround2:{backgroundColor:'red'},
})

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM