简体   繁体   English

React Native-尝试更新金额,但从父级传递给子级时未正确更新

[英]React Native - Trying to update an amount but it's not updating properly when passing down from parent to child

I'm trying to make a Tip Calculator app with React Native where the user inputs a total amount on the text field, and the tip amount will be shown to the user as shown below. 我正在尝试使用React Native创建一个小费计算器应用程序,其中用户在文本字段上输入总金额,小费金额将显示给用户,如下所示。 在此处输入图片说明

As you can see, the amount is off and the reason is probably how I'm taking in my text input: 如您所见,数量已减少,原因可能是我输入文字的方式:

<Text>Total Amount: </Text>
    <TextInput
    style={styles.textInputContainer}
    onChangeText={this.handleTotalAmount}
    onSubmitEditing={this.handleTotalAmount}
    />

However, I did find a workaround where if I use onSubmitEditing as well, the field will properly update when I hit return. 但是,我确实找到了一种解决方法,如果我也使用onSubmitEditing ,则当我按下return时该字段将正确更新。 This doesn't really sit well with me because I feel like I'm hacking it together without really knowing how it's working and that I also feel like there's a better solution to passing down an updating value to another class. 这对我来说并不太好,因为我感觉自己在不了解它的工作原理的情况下就将其混为一谈,而且我还觉得有一个更好的解决方案可以将更新的值传递给另一个类。

Here are other bits of my code if it is helpful in showing how I structured my app. 如果有助于显示我的应用程序结构,这是我的代码的其他内容。 I have a class TotalAmount that has a TextInput that will take in a totalAmount , and I want to pass that totalAmount into my class TipAmount15 to calculate the tip amounts. 我有一个TotalAmount类, TotalAmount具有一个TextInput ,它将接受一个totalAmount ,我想将该totalAmount传递到我的类TipAmount15以计算小费金额。 I was able to have everything in a single class, but because I want to add more tip amounts, I wanted to separate the classes. 我可以将所有内容都放在一个类中,但是因为我想增加更多的小费金额,所以我想将这些类分开。 Please let me know if there's a better way of updating or if there's a better TextInput property to use than onChangeText or onSubmitEditing ! 请让我知道是否有比onChangeTextonSubmitEditing更好的更新方式或是否有更好的TextInput属性使用! Help is much appreciated. 非常感谢您的帮助。

class TotalAmount extends Component {
  constructor(props) {
    super(props);
    this.state = {
      totalAmount: ''
    }
  }

  handleTotalAmount = (totalAmountInput) => {
    this.setState({
      totalAmount: totalAmountInput
    })
}


render() {

    return (
      <View>
      <View style={styles.totalAmountContainer}>
          <Text>Total Amount: </Text>
            <TextInput
            style={styles.textInputContainer}
            onChangeText={this.handleTotalAmount}
            onSubmitEditing={this.handleTotalAmount}
            />  
      </View>
      <TipAmount15 
        percent={15}
        totalAmount={this.state.totalAmount}/>
      </View>
    )
  }
}

class TipAmount15 extends Component {
  constructor(props) {
    super(props);
    this.state = {
      percent: '',
      totalAmount: '',
      tipAmount15:'',
      postTipAmount15:''
    }
  }
  componentWillReceiveProps(props) {
    var percent = this.props.percent;
    var totalAmountInput = this.props.totalAmount;
    this.setState({totalAmount: totalAmountInput})
//Calculate Tip Percentages
    this.setState({tipAmount15: parseFloat(totalAmountInput*(percent/100)).toFixed(2)})
    this.setState({postTipAmount15: parseFloat(totalAmountInput * (1+(percent/100))).toFixed(2)})
  }

  render() { 
    return (
      <View style={styles.tipCalculatorContainer}>     
            <Text>{this.props.percent}%</Text>
            <Text>Tip Amount: {this.state.tipAmount15}</Text>
            <Text>Total Amount: {this.state.postTipAmount15}</Text>
        </View>
    )
  }
}

Couple thoughts: 夫妻想法:

1) You should be able to refactor TipAmount to something a bit simpler eg (note need to type convert at the end in this example) 1)您应该能够将TipAmount重构为更简单的内容,例如(请注意,在此示例的最后需要键入convert)

const TipAmount15 = ({ percent, totalAmount }) => {
  const tipAmount = parseFloat(totalAmount * (percent/100)).toFixed(2)

  return (
    <View style={styles.tipCalculatorContainer}>     
      <Text>{this.props.percent}%</Text>
      <Text>Tip Amount: {tipAmount}</Text>
      <Text>Total Amount: {Number(totalAmount) + Number(tipAmount)}</Text>
    </View>
  )
}

because all we are doing is a couple calculations for presentation to User. 因为我们要做的只是几次计算,以呈现给用户。 Everything we display can be easily converted from the given props so there is no real need for this component to hold its own state. 我们显示的所有内容都可以轻松地从给定的props进行转换,因此并不需要此组件保持其自身的状态。

2) Why does the TextInput in the TotalAmount component need to handle both onChange and submit if they are both just calling the same handler? 2)为什么会发生TextInputTotalAmount组件需要同时处理onChangesubmit ,如果他们都只是调用相同的处理? I do not think you need both in this case. 在这种情况下,我认为您不需要两者。

The issue was I was incorrectly using componentWillReceiveProps . 问题是我不正确地使用componentWillReceiveProps

 componentWillReceiveProps(newProps) {
    if(newProps.totalAmount != this.props.totalAmount){
      var percent = this.props.percent;
      var totalAmountInput = newProps.totalAmount;
      this.setState({totalAmount: totalAmountInput});
      this.setState({tipAmount15: parseFloat(totalAmountInput*(percent/100)).toFixed(2)})
      this.setState({postTipAmount15: parseFloat(totalAmountInput * (1+(percent/100))).toFixed(2)})
    }
  }

When checking if there has been a change, it now properly updates with the text field onChangeText and solved my issue. 现在,当检查是否有更改时,它会使用文本字段onChangeText正确更新,并解决了我的问题。

However, even though this did solve my original issue, I'm still unaware if there is a better way of passing the information through. 但是,尽管这确实解决了我原来的问题,但我仍然不知道是否有更好的信息传递方式。

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

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