Javascript 更改按钮颜色 onPress(切换功能)React Native

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/32347605/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-23 07:55:57  来源:igfitidea点击:

Change Button Color onPress (toggle functionality) React Native

javascriptuser-interfacebuttonreact-native

提问by Robert Tomas G IV

hope all is well.

希望一切顺利。

I seem to be having difficulty with a basic button functionality. All I need is the state of the class to change and the button style to change every-time the button is pressed. Unlike TouchableHighlight, I need to color change to stay until the button is pressed again (to go back to the original color).

我似乎无法使用基本的按钮功能。我所需要的只是每次按下按钮时要更改的类的状态和要更改的按钮样式。与 TouchableHighlight 不同,我需要保持颜色变化,直到再次按下按钮(恢复到原始颜色)。

I have tried to use SwitchIOS but it doesn't seem to be easily styled into a circular button, and therefore doesn't really work out. I am a novice so still learning and would greatly appreciate your help. Here is what I have so far:

我曾尝试使用 SwitchIOS,但它似乎并不容易被设计成圆形按钮,因此并没有真正起作用。我是新手,所以仍在学习,非常感谢您的帮助。这是我到目前为止所拥有的:

'use strict';

var React = require('react-native');
var Dimensions = require('Dimensions');
var window = Dimensions.get('window');
var Icon = require('react-native-vector-icons/FontAwesome');
var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  NavigatorIOS,
  Image, 
  TouchableHighlight,
  TextInput,
} = React;


class LS1 extends React.Component{

  constructor(props){
    super(props);
    this.state = {
      paleo: false, 
      vegan: false, 
      vegetarian: false, 
      nutfree: false, 
      dairyfree: false, 
      healthy: false,
      glutenfree: false,
    }
  }

  SkipLogin() {
    var num = window.height/8.335;
    console.log(num);
  }

  render() {
    return (
      <View style={styles.container}>
        <Image source={require('image!LS1')} style={styles.bgImage}>
          <Text style={styles.icontext}>Help us get to know your dietary lifestyle.</Text>

          <View style={styles.container}>
            <View style={{flex: 1, alignItems: 'center', flexDirection: 'row',justifyContent: 'center',marginTop:-20}}>
              <TouchableHighlight underlayColor='rgba(73,182,77,1,0.9)' style={styles.bubblechoice}>
                  <Image style={styles.bubblechoice} source={require('image!vegan')}>
                    <View style={styles.overlay}>
                      <Text style={styles.choicetext}>Vegan</Text>
                    </View>
                  </Image>
              </TouchableHighlight>
              <TouchableHighlight underlayColor='rgba(73,182,77,1,0.6)' style={styles.bubblechoice} >
                <Image style={styles.bubblechoice} source={require('image!paleo')}>
                  <View style={styles.overlay}>
                    <Text style={styles.choicetext}>Paleo</Text>
                  </View>
                </Image>
              </TouchableHighlight>
              <TouchableHighlight underlayColor='rgba(73,182,77,1,0.6)' style={styles.bubblechoice} >
                <Image style={styles.bubblechoice} source={require('image!nutfree')}>
                  <View style={styles.overlay}>
                    <Text style={styles.choicetext}>Nut-Free</Text>
                  </View>
                </Image>
              </TouchableHighlight>
              <TouchableHighlight underlayColor='rgba(73,182,77,1,0.6)' style={styles.bubblechoice} >
                <Image style={styles.bubblechoice} source={require('image!glutenfree')}>
                  <View style={styles.overlay}>
                    <Text style={styles.choicetext}>Gluten-Free</Text>
                  </View>
                </Image>
              </TouchableHighlight>
            </View>

            <View style={{flex: 1, alignItems: 'center', flexDirection: 'row',justifyContent: 'center',marginTop:-50}}>
              <TouchableHighlight underlayColor='rgba(73,182,77,1,0.6)' style={styles.bubblechoice} >
                <Image style={styles.bubblechoice} source={require('image!dairyfree')}>
                  <View style={styles.overlay}>
                    <Text style={styles.choicetext}>Dairy-Free</Text>
                  </View>
                </Image>
              </TouchableHighlight>
              <TouchableHighlight underlayColor='rgba(73,182,77,1,0.6)' style={styles.bubblechoice} >
                <Image style={styles.bubblechoice} source={require('image!vegetarian')}>
                  <View style={styles.overlay}>
                    <Text style={styles.choicetext}>Vegetarian</Text>
                  </View>
                </Image>
              </TouchableHighlight>
              <TouchableHighlight underlayColor='rgba(73,182,77,1,1)' style={styles.bubblechoice} >
                <Image style={styles.bubblechoice} source={require('image!healthy')}>
                  <View style={styles.overlay}>
                    <Text style={styles.choicetext}>Healthy</Text>
                  </View>
                </Image>
              </TouchableHighlight>
            </View>
          </View>

          <Image source={require('image!nextbtn')} style={{resizeMode: 'contain', width:200, height:50, alignSelf: 'center', marginBottom: 50}}/>

          <TouchableHighlight onPress={this.SkipLogin.bind(this)} underlayColor='transparent'>
            <View style={{backgroundColor: 'transparent', alignItems: 'center', marginBottom: 8}}>
              <Text>skip this step</Text>
            </View>
          </TouchableHighlight>

        </Image>
      </View>
    );
  }
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'transparent'
  },
  bgImage: {
    flex: 1,
    width: window.width,
    resizeMode: 'cover',
  },
  icontext: {
    color: '#5d5d5d',
    fontWeight: '400',
    fontSize: 20,
    backgroundColor: 'transparent',
    paddingLeft: 10,
    alignItems: 'center',
    marginTop: window.height/2.2,
    textAlign: 'center',
    margin: 10,
  },
  bubblechoice_click: {
    height: window.height/8.335,
    borderRadius: (window.height/8.3350)/2,
    marginRight: 2,
    width: window.height/8.335,
  },
  bubblechoice: {
    height: window.height/8.335,
    borderRadius: (window.height/8.3350)/2,
    marginRight: 2,
    width: window.height/8.335,
  },
  row: {
    flex: 1,
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: -30,
  },
  choicetext: {
    alignItems: 'center',
    alignSelf: 'center',
    color: 'white',
    marginTop: 35,
    fontWeight: '600',
    marginLeft: -18,
    fontSize: 14,
    flex: 1,
    textAlign: 'center'
  },
  overlay: {
    backgroundColor:'rgba(80,94,104,0.7)',
    height: 100,
    width: 100,
    alignItems:'center'
  },

});

module.exports = LS1;

And here is a visual of what that produces:

这是产生什么的视觉效果:

Frame when all buttons are un-pressed

取消按下所有按钮时的帧

Here's what the button should look like after being selected:

下面是按钮被选中后的样子:

Frame when button is pressed

按下按钮时的帧

回答by brentvatne

I think you should take a step back and do some basic React tutorials before digging too much into React Native - this is a fairly straightforward problem to solve :) Here's a solution for you:

我认为你应该退后一步,在深入研究 React Native 之前先做一些基本的 React 教程——这是一个相当简单的问题来解决:) 这是一个适合你的解决方案:

'use strict';

var React = require('react-native');
var Dimensions = require('Dimensions');
var window = Dimensions.get('window');

var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  NavigatorIOS,
  Image,
  TouchableHighlight,
  TextInput,
} = React;

class ToggleButton extends React.Component {

  render() {
    return (
      <TouchableHighlight underlayColor='rgba(73,182,77,1,0.9)' style={styles.bubblechoice} onPress={this.props.onPress}>
          <Image style={styles.bubblechoice} source={{uri: 'https://facebook.github.io/react/img/logo_og.png'}}>
            <View style={[styles.overlay, this.props.selected ? {backgroundColor: 'rgba(80,94,104,0)'} : {}]}>
              <Text style={styles.choicetext}>{this.props.label}</Text>
            </View>
          </Image>
      </TouchableHighlight>
    );
  }
}


class LS1 extends React.Component{

  constructor(props){
    super(props);
    this.state = {
      paleo: false,
      vegan: false,
      vegetarian: false,
    }
  }

  updateChoice(type) {
    let newState = {...this.state};
    newState[type] = !newState[type];
    this.setState(newState);
  }

  SkipLogin() {
    var num = window.height/8.335;
    console.log(num);
  }

  render() {
    return (
      <View style={styles.container}>
        <View style={styles.bgImage}>
          <Text style={styles.icontext}>Help us get to know your dietary lifestyle.</Text>

          <View style={styles.container}>
            <View style={{flex: 1, alignItems: 'center', flexDirection: 'row',justifyContent: 'center',marginTop:-20}}>
              <ToggleButton label='Vegan' onPress={() => { this.updateChoice('vegan') }} selected={this.state.vegan} />
              <ToggleButton label='Paleo' onPress={() => { this.updateChoice('paleo') }} selected={this.state.paleo} />
              <ToggleButton label='Vegetarian' onPress={() => { this.updateChoice('vegetarian') }} selected={this.state.vegetarian} />
            </View>
          </View>

          <TouchableHighlight onPress={this.SkipLogin.bind(this)} underlayColor='transparent'>
            <View style={{backgroundColor: 'transparent', alignItems: 'center', marginBottom: 8}}>
              <Text>skip this step</Text>
            </View>
          </TouchableHighlight>

        </View>
      </View>
    );
  }
};

var styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    backgroundColor: 'transparent'
  },
  bgImage: {
    flex: 1,
    width: window.width,
    resizeMode: 'cover',
  },
  icontext: {
    color: '#5d5d5d',
    fontWeight: '400',
    fontSize: 20,
    backgroundColor: 'transparent',
    paddingLeft: 10,
    alignItems: 'center',
    marginTop: window.height/2.2,
    textAlign: 'center',
    margin: 10,
  },
  bubblechoice_click: {
    height: window.height/8.335,
    borderRadius: (window.height/8.3350)/2,
    marginRight: 2,
    width: window.height/8.335,
  },
  bubblechoice: {
    height: window.height/8.335,
    borderRadius: (window.height/8.3350)/2,
    marginRight: 2,
    width: window.height/8.335,
  },
  row: {
    flex: 1,
    alignItems: 'center',
    flexDirection: 'row',
    justifyContent: 'center',
    marginTop: -30,
  },
  choicetext: {
    alignItems: 'center',
    alignSelf: 'center',
    color: 'white',
    marginTop: 35,
    fontWeight: '600',
    marginLeft: -18,
    fontSize: 14,
    flex: 1,
    textAlign: 'center'
  },
  overlay: {
    backgroundColor:'rgba(80,94,104,0.7)',
    height: 100,
    width: 100,
    alignItems:'center'
  },

});

module.exports = LS1;

AppRegistry.registerComponent('main', () => LS1);

You can try it out by downloading Exponent to your phone from http://exponentjs.com/(app store or beta, whichever you prefer) then loading up exp://exp.host/@brentvatne/button-color-exp

您可以通过从http://exponentjs.com/(应用商店或测试版,无论您喜欢哪个)下载 Exponent 到您的手机,然后加载 exp://exp.host/@brentvatne/button-color-exp 来试用它

回答by Javlon Tulkinov

Simplest way with TouchableOpacityand active styles:

使用TouchableOpacity和活动样式的最简单方法:

<TouchableOpacity
style={ this.state.active? styles.btnActive : styles.btn}
onPress={() => this.setState({active: !this.state.active})}>

</TouchableOpacity>