How do Textinput print number 1 every time you press Buttom?

Asked

Viewed 29 times

1

How to do the TextInput print out the number 1 every time we press the button?

Example: if I press 5 times the button, I want "11111" to appear on TextInput.

const App = () => {

  const state={
    newNumber: 1,
    number: ''
  };

  const printNumber = () => {
     const resultado = this.state.newNumber;

     this.setState({
       number: resultado
     });
  }

  return (
    <View style={styles.container}>
      
      <TextInput
        style={styles.input}
         value={this.number}
        onChangeText={(text) =>this.setState({number})}
      />
      
      <Button title="1" onPress={printNumber} />
    </View>
  );
}

1 answer

1


You have a problem with your code in your code, you cannot start the same state was with component (see my example).

Basically, the code is to concatenate the existing values with a text that represents the number "1", that in the language needs the value to be concatenated to be a text, minimum example:

const App = () => {
  const [n, setN] = React.useState(''); 
  const handleChange = (e) => setN(state => state + "1");
  return (
    <div>
      <input type="text" value={n} onChange={e => setN(e.target.value)} />
      <button onClick={handleChange}>adicionar</button>
    </div>
  )
}

ReactDOM.render( <App/> , document.getElementById('root'));
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.9.0/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.9.0/umd/react-dom.production.min.js"></script>
<div id="root">Carregando ...</div>

Observing: the snippet here is , but the concept is the same for


In your code it’s basically:

const App = () => {
    const [number, setNumber] = React.useState(''); 
    
    const printNumber = () => {
        setNumber(state => state + "1");
    }
    
    return (
        <View style={styles.container}>   
            <TextInput
                style={styles.input}
                value={this.number}
                onChangeText={(text) => setNumber(state => state + text)}
            />    
            <Button title="1" onPress={printNumber} />
        </View>
    );
}

this way will work typing and also when press the button.

  • 1

    Thank you very much. I got the idea. I pasted the code and removed the "this" that was in the Textinput value. It worked perfect.

  • If useful @Marcoscruz reply check as response to help the community

  • I don’t know how to do.

  • @Marcoscruz please read: https://pt.meta.stackoverflow.com/questions/1078/como-e-por-que-aceitar-uma-resposta simply tick the answer and Positive if you so wish (up arrow you have given a useful answer and the check below arrow is accepting as answer to your question) read the answers

Browser other questions tagged

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