1

I want print the value which is entered in TextInput to console.

below is snippets from my code:

constructor(props) {
        super(props);
        this.state= {
            textValue: "",
        }
    }
    _textChange = (text) => {
        this.setState({
            textValue: text,
        })
        console.log(this.state.textValue);
}

AND:

<TextInput onChange={this._textChange.bind(this)}/>

I know that something is wrong with my code, but I am not able to figure it out. I just want to print the entered text in TextInput to be printed in console

Note

I have seen this answer. I am not able to understand the answers in the given link. I am very new to react-native. So please try to explain it the simple way.

halfer
  • 19,824
  • 17
  • 99
  • 186
pratteek shaurya
  • 850
  • 2
  • 12
  • 34

3 Answers3

1

You should use onChangeText instead of onChange

<TextInput onChangeText={this._textChange}/>

if declare your method as a named function like below

    _textChange(text) {
        this.setState({
            textValue: text,
        })
     }

So you should use bind, because the this keyword will not refer to the component scope,but in your case it is not necessary.

Please take a look at this article to understand difference between named function and arrow function.

ARZMI Imad
  • 950
  • 5
  • 8
1

setState() function in any component is asynchronous or is called after the completion of the function that it was called in.If you want to see the result of the console, you can do this:

  this.setState({
       textValue: text,
    },() => {
        console.log(this.state.textValue);
    });
zahra zamani
  • 1,323
  • 10
  • 27
0

You are missing something when you create a class but your error is inside the react event onChangeText instead of onChange, but I think you can avoid calling this._textChange.bind(this), this is used with another type of class declaration (see below). I like the following react class declaration, and maybe it can help to understand what is happening under the hood (if you are starting with react now)

class PComponern extends Component {

    constructor(props) {
        super(props);
        this.state= {
            textValue: "",
        };
       this._textChange = this._textChange.bind(this)
    }
 
  _textChange(text) {
    this.setState({
            textValue: text,
        });
    console.log(this.state.textValue);
  }   

  render (
    ...
    <TextInput onTextChange={this._textChange}/>
    ...
    )
   
}

This form can help you to start, but sometimes in not necessary call the this._textChange = this._textChange.bind(this) in the constructor, see also this reference

There are also a couple of comment that suggest the following things

  • you may want to do this: onTextChange={this._textChange} instead of using onChange.

Runnable code

vincenzopalazzo
  • 1,487
  • 2
  • 7
  • 35