React Native:如何在onPress期间修复Button组件的错误?

时间:2019-05-06 07:43:10

标签: javascript react-native

我正在尝试向组件中添加<Button />,以通过在按下总数时向总数添加数字来更新组件的状态。我不确定我设置的功能是否不正确,或者按钮设置不正确。

我可以在没有<Button/>组件的情况下很好地运行代码,但是当将其添加到我的组件时,应用程序崩溃。

这是我的代码:

import React, {Component} from 'react';
import {Platform, StyleSheet, Text, View} from 'react-native';
import { AppRegistry, Image } from 'react-native';
import { Button } from 'react-native'

export default class Money extends Component {
  constructor(props) {
    super(props);
    this.state = {
      money: 5,
      tomatoes: 0
    };
  }

  addMoreMoney() {
    this.setState({
      money: this.state.money + 65
    });
  } 

  render() {
    return (<View style={{alignItems: 'center', top:50}}>
    <Text> You have {this.state.money} left in your account </Text>

    <Button
    onPress={() => this.addMoreMoney()}
    title="Add it Up!"
    color:"#B22222"
    accessibilityLabel="Add money to account by 65 by pressing this button"
    />

    </View>);
  }
}  

我希望按此按钮可以增加金额。它应该从5开始并相应地增加。

2 个答案:

答案 0 :(得分:2)

问题似乎是您将color道具分配给<Button>的方式。

如果您更新render()方法,以便color分配color="#B22222"来解决您的问题,则:

render() {
    return <View style={{alignItems: 'center', top:50}}>
    <Text>You have {this.state.money} left in your account</Text>

    <Button
    onPress={() => this.addMoreMoney()}
    title="Add it Up!"
    color="#B22222"
    accessibilityLabel="Add money to account by 65 by pressing this button"/>
    </View>
}

答案 1 :(得分:1)

您正在发生意外的令牌错误:

更改:

 <Button
        onPress={() => this.addMoreMoney()}
        title="Add it Up!"
        color:"#B22222"
        accessibilityLabel="Add money to account by 65 by pressing this button"
 />

收件人

// color="#B22222" 
<Button
        onPress={() => this.addMoreMoney()}
        title="Add it Up!"
        color="#B22222" 
        accessibilityLabel="Add money to account by 65 by pressing this button"
 />

输出:

example

工作示例:https://snack.expo.io/rJo-twpi4