React Native-未定义的onPress for TextInput函数

时间:2018-07-19 17:22:53

标签: javascript android reactjs react-native mobile

我试图在我的应用中创建一个递增和递减按钮,然后在我的textinput中显示该数字,但是由于某种原因,textinput没有显示预期的输出。我不确定按钮的功能是否缺少部分或文本输入。

编辑:我仍然不确定,但是我的功能是:“ _incrementCount”和 在我的console.log和警报中未定义“ _decreaseCount”。

并且没有“ string()”,我正在警告。

这是我的代码:

export default class Dishes extends Component {
    constructor(props) {
        super (props)
        this.state = {
            count: 0,
        }
    }
    _incrementCount(index) {
        this.setState({ ['count'+index]: this.state['count'+index] + 1 });
        console.log(this.count);
        alert(this.count);
    }
    _decreaseCount(index) {
        this.setState({ ['count'+index]: this.state['count'+index] - 1 });
        console.log(this.count);
        alert(this.count);
    }
    changeTextHandler(text) {
        this.setState({ ['count'+index]: text });
    };

    _renderItem = ({ item, index }) => {
     return (
        <View>
            <TouchableOpacity
                onPress = {() => this._incrementCount(index)}>
                <Text style = {styles.buttonText}> + </Text>
            </TouchableOpacity>

            <TextInput
                onChangeText={ (text) => this.changeTextHandler(text) }
                value={ this.state.count }
                keyboardType = "numeric"
                placeholder="0"
            />

            <TouchableOpacity
                onPress = {() => this._decreaseCount(index)}>
                <Text style = {styles.buttonText}> - </Text>
            </TouchableOpacity>
        </View>
     )
    }

enter image description here

1 个答案:

答案 0 :(得分:0)

您做错了很多事情,但我想这就是您所需要的。您可以检查this expo snack to confirm。在开始使用react native之前,您需要学习一些react基础知识,there docs是一个入门的好地方

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

export default class Dishes extends Component {
  state = {
    count: 0,
  };

  _incrementCount = () => {
    this.setState(({ count }) => ({ count: count + 1 }));
  };

  _decreaseCount = () => {
    this.setState(({ count }) => ({ count: count - 1 }));
  };

  render() {
    return (
      <View style={styles.container}>
        <TouchableOpacity onPress={this._incrementCount}>
          <Text style={styles.buttonText}> + </Text>
        </TouchableOpacity>

        <Text>{this.state.count}</Text>

        <TouchableOpacity onPress={this._decreaseCount}>
          <Text style={styles.buttonText}> - </Text>
        </TouchableOpacity>
      </View>
    );
  }
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: 'center',
    alignItems: 'center',
    flexDirection: 'row',
  },
  buttonText: {
    backgroundColor: 'red',
    margin: 5,
    padding: 5,
  },
});