使用React-Native在控制台中打印状态值

时间:2018-03-19 07:40:15

标签: reactjs react-native console react-native-android

我需要在控制台中打印TextInput值,但是当我尝试这样做时,我会在屏幕截图中收到错误,或者当我输入用户名TextInput时它会自动删除。提前致谢

enter image description here

import React, { Component } from 'react';
import {TextInput , Button , View } from 'react-native';

export default class Profile extends Component {
  constructor(){
    super()
      this.state = {
        text:''
      }
    }
  handleChangeText = (typedText) => {
    this.setState({text:typedText});
    console.log(this.state.text);
  }
  render() {
    return (
            <View> 
                <TextInput 
                   placeholder="Enter your Username" 
                   value={this.state.text}/>
                <Button 
                title="Submit" 
                onPress={this.handleChangeText} />
            </View>
      );
    }
  }

4 个答案:

答案 0 :(得分:3)

尝试将TextInput代码更改为此(您缺少onChangeText ):

<TextInput placeholder={'Enter your Username'}
           onChangeText={this.handleChangeText}
           value={this.state.text} />

顺便说一下,setState不会立即更改该值。因此,在this.setState()之后放置console.log可能不会显示正确的值。

答案 1 :(得分:3)

您的handleChangeText应与<TextInput>相关联,而不是与<Button>相关联。您需要在change handler属性中传递onChangeText。请尝试如下。

<TextInput 
  onChangeText={this.handleChangeText} 
  placeholder="Enter your Username" 
  value={this.state.text}
/>

希望这会有所帮助。

答案 2 :(得分:3)

您的handleChangeText函数应该在TextInput onChangeText道具中使用,以便您可以使用正确的值更新状态。

更改您的代码,如下所示;

import React, { Component } from 'react';
import {TextInput , Button , View } from 'react-native';

export default class Profile extends Component {
  constructor(){
    super()
      this.state = {
        text:''
      }
    }
  handleChangeText = (typedText) => {
    this.setState({text:typedText}, () => {
      console.log(this.state.text);
    });
  }
  handleSubmit = (event) => {
    // do something after submit
  }
  render() {
    return (
            <View> 
                <TextInput 
                   placeholder="Enter your Username" 
                   onChangeText={this.handleChangeText}
                   value={this.state.text}/>
                <Button 
                title="Submit" 
                onPress={this.handleSubmit} />
            </View>
      );
    }
  }

PS: this.setState是一个异步函数,因此您需要使用回调来读取状态值,如上图所示。

答案 3 :(得分:2)

您的TextInput处理文本的更改。

handleChangeText(text) {
  this.setState(text); // this is async
  console.log(this.state.text) // could be the old state 
}

<TextInput 
placeholder="Enter your Username" 
value={this.state.text}
onChangeText={(text) => this.handleChangeText(text)}
/>

您可以找到有关react-native的TextInputs here

的更多信息