How to use state in a function?

Asked

Viewed 1,443 times

1

I have the following code:

export default class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      xsemana: '0',
      meses: '1',
      minutos: '1',
    };
  }

  calcula(){
    const total = this.state.xsemana *
    (52 * this.state.meses / 12) *
    this.state.minutos;
    alert(total);
  }

  render() {
return (
  <View style={styles.container}>
    <Text>Vezes por semana</Text>
    <TextInput style={styles.input} keyboardType='numeric' onChangeText={(text) => this.setState({xsemana: text.replace(/[^0-9]/g, ''),})} value={this.state.xsemana} />

    <Text>Quantos meses?</Text>
    <TextInput style={styles.input} keyboardType='numeric' onChangeText={(text) => this.setState({meses: text.replace(/[^0-9]/g, ''),})} value={this.state.meses} />

    <Text>Quantos minutos?</Text>
    <TextInput style={styles.input} keyboardType='numeric' onChangeText={(text) => this.setState({minutos: text.replace(/[^0-9]/g, ''),})} value={this.state.minutos} />

    <View style={{flex:1, backgroundColor:'red'}}>
      <Button title="Calcular" color="#417ee0" style={{height:80}} onPress={this.calcula}/>
    </View>

  </View>
  );
}
}

I want to do a function calculation calcula(), using the values of state above.

However, I am getting the error:

Undefined is not an Object (evaluating 'this.state.xsemana')

How to use in my function, the states created above?

  • When you call this function ?

  • @wmsouza put the full code

1 answer

2


  • I’ll test it. Voce can explain what the bind is for?

  • 1

    @Italorodrigo edited the answer and put a question asked here on Sopt

Browser other questions tagged

You are not signed in. Login or sign up in order to post.