繁体   English   中英

在React Native中使用TouchableHighlight组件按下按钮时,如何使2个动作发生?

[英]How to make 2 actions happen when a button is pressed with the TouchableHighlight component in React Native?

按下按钮后,我设法使控制台输出文本。 但是,我也希望每次点击都增加一个名为nClicks的全局变量的值,但是一直很难做到。 这是我的代码:

/**
 * Sample React Native App
 * https://github.com/facebook/react-native
 */
'use strict';

var React = require('react-native');
 var {
  AppRegistry,
  StyleSheet,
  Text,
  View,
  TouchableHighlight,
        } = React;

        var nClicks = 0;

        var simple = React.createClass({
        render: function() {
        return (
        <View style={styles.container}>
        <Text style={styles.welcome}>
        Tap the button as fast as you can!
        </Text>

        <TouchableHighlight style={styles.button}
        onPress={() =>

        nClicks++,
        console.log('pressed')}>

        <Text style={styles.buttonText}>
         Tap Here!
        </Text>

        </TouchableHighlight>

  </View>
);
}
});

var styles = StyleSheet.create({
container: {
flex: 1,
justifyContent: 'center',
alignItems: 'center',
backgroundColor: '#F5FCFF',
},
welcome: {
fontSize: 30,
textAlign: 'center',
                           marginTop: -280,

},
instructions: {
textAlign: 'center',
color: '#333333',
marginBottom: 5,
},

                           button:{
                           width: 250,
                           height: 100,
                           borderColor: 'red',
                           borderWidth: 3,
                           borderRadius: 5,
                           marginTop: 60,

                           justifyContent: 'center',

                           alignItems: 'center',
                           textAlign: 'center',
                           color: 'red',

                           },

                           buttonText:{
                           fontSize: 20,
                           }



                        });

AppRegistry.registerComponent('simple', () => simple);

您可以使用计数器初始化为类创建一个构造函数:

class YourClass extends React.Component {
    constructor(props) {
        super(props);
        this.state = {
           count: 0
       }
   }
   render() {
      //......
   }
};

然后,当您按下TouchableHighlight组件时,您必须增加count变量。

this.setState({
    count: this.state.count + 1
})

这是可能的,因为每个组件都有一个状态对象(也有一个props对象)。 使用setState方法设置此状态。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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