简体   繁体   中英

React Native, setting value of item in state incorrectly

    constructor(props) {
            super(props);
            this.state = {
              message: "..",
            };
    }
    render() {
      return (
          <View style={styles.container}>

            <View style={styles.textInput}>

              <TextInput onChangeText={(message) => this.setState({message})} placeholder="Enter your message..." style={styles.text}/>

              <TouchableHighlight style={styles.button} onPress={this.submit}>

                <Text ref="message" onPress={this.submit}>Submit</Text>

              </TouchableHighlight>

            </View>

          </View>
        )
    }

    loadData(){
      AlertIOS.alert(this.state.message);
    }
    componentDidMount(){
      this.loadData()
    }
    submit(){
      AlertIOS.alert(this.state.message);
    }

When loadData is first called, it shows the current value of message: ".."

When my submit function is called, it throws an error: undefined is not an object (evaluating 'this.state.message')

I'm assuming that it is my onChangeText attribute that's setting message to undefined, but I'm not sure why.

The problem is that this isn't bound correctly in submit()

In your constructor, try adding the line:

this.submit = this.submit.bind(this);

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