react native get TextInput value

前端 未结 16 2051
一生所求
一生所求 2020-12-04 16:10

I am stuck with a very simple problem. I have login form with username, password and button. In my button handler, I try to get the textinput value. But always get undefined

16条回答
  •  一向
    一向 (楼主)
    2020-12-04 16:47

    The quick and less optimized way to do this is by using arrow function inside your onChangeText callback, by passing username as your argument in your onChangeText callback.

     { this.username = el; }}
        onChangeText={(username) => this.setState({username})}
        value={this.state.username}
    />
    

    then in your _handlePress method

    _handlePress(event) {
        let username=this.state.username;
    }
    

    But this has several drawback!!!

    1. On every render of this component a new arrow function is created.
    2. If the child component is a PureComponent it will force re-renders unnecessarily, this causes huge performance issue especially when dealing with large lists, table, or component iterated over large numbers. More on this in React Docs

    Best practice is to use a handler like handleInputChange and bind ```this`` in the constructor.

    ...
    constructor(props) {
      super(props);
      this.handleChange= this.handleChange.bind(this);
    }
    
    ...
    handleChange(event = {}) {
      const name = event.target && event.target.name;
      const value = event.target && event.target.value;
    
      this.setState([name]: value);
    }
    ...
    
    render() {
      ...
      
      ...
    }
    
    ...
    

    Or if you are using es6 class property shorthand which autobinds this. But this has drawbacks, when it comes to testing and performance. Read More Here

    ...
    handleChange= (event = {}) => {
      const name = event.target && event.target.name;
      const value = event.target && event.target.value;
    
      this.setState([name]: value);
    }
    ...
    
    render() {
      ...
      
      ...
    }
    
    ...
    

提交回复
热议问题