React Native,设置状态值不正确

时间:2016-03-09 22:27:56

标签: javascript react-native

    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);
    }

首次调用loadData时,它会显示消息的当前值:“..”

调用submit函数时,会抛出错误:undefined is not an object (evaluating 'this.state.message')

我假设我的onChangeText属性将消息设置为undefined,但我不确定原因。

1 个答案:

答案 0 :(得分:1)

问题是this

中未正确绑定submit()

在构造函数中,尝试添加以下行:

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