简体   繁体   中英

add one to textinput value on button press in react-native

I have this button and input

 <Button style={styles.button, {overflow: 'hidden' }} onPress={this.ADDONE}>   ADD </Button>
 <TextInput ref={component => this._textInput = component}
 style={{height: 40, borderColor: 'gray',width:120}
           value={this.state.text}  defaultValue='N.m' />

and here is my try

ADDONE:function(){      
   var va=this.state._textInput;      
   if(va == "" || va == "undefined"){va=0}    
   va=va+1;
    this._textInput.setNativeProps({text: va});    
},

what I need is when I press on button to add 1 to input value every time the button event is "onpress=function"

Now it can't increase 1 because it is string not number I tried this

var va=this.state._textInput;
  var  nn= {properties: { value: 0 }};
   if(va == 'N.m' || va == undefined){va=0;}
nn=va;
   nn=nn+1;
 va = nn ;
    this._textInput.setNativeProps({text: va});

it just give a right behvaior at the first time only after that it can't parse text to int please help

Maybe you're trying to do something I'm not quite understanding, but this seems over-engineered to me. If all you need is to add +1 to a variable when a button is pressed, then try this...

constructor(props){
   this.super(props);
   this.state = {
      va = 0,
   }
}

render(){
  <Button
    onPress={() => this.setState({va: this.state.va++})} >
    ADD
  </Button>
}

And by the way, I'm pretty sure you need to update your style declaration by wrapping it in an array like so...

style={[styles.button, {overflow: 'hidden' }]}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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