如何使用本机反应在控制台中打印状态? [英] how to print state in console with react native?

查看:35
本文介绍了如何使用本机反应在控制台中打印状态?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图在控制台中打印状态以进行调试但收到错误消息

I am trying to print the state in console for debugging but getting error message

无法读取未定义的属性 'petname'

在控制台中打印状态的正确方法是什么,为什么将其称为属性?

What is the right way to print state in console and why this is calling it a property?

export default class App extends Component<{}> {
  constructor(props) {
    super(props)

    this.state = {
      petname: '',
      owner: ''
    };
  }
  
  addPet() {
    console.log("Button Pressed");
    console.log(this.state.petname);
    return (
      //some logic
    );
  }
  
  render() {
    return (
      <View style={styles.container}>
        <View style={styles.inputStyle}>
          <Text>Pet</Text>
          <TextInput onChangeText={petname =>                                 this.setState({petname})} style={{width:100}} />
        </View>
        <View style={styles.inputStyle} >
          <Button title="Add Pet" onPress={this.addPet} />
        </View>
      </View>
    )
  }
}

推荐答案

this 在您的函数中不可访问.您可以将 thisonPress 上的函数绑定,或者您可以在构造函数中编写以下内容.

this is not accessible in your function. Either you can bind this with your function on onPress or you can write following in your constructor.

this.addPet = this.addPet.bind(this); 

比较第一个和第二个选项,第二个选项更好,因为它不会每次都创建新实例.

Comparing 1st and 2nd option, 2nd option is better because it doesn't create new instance every time.

最好的选择是使用箭头函数(ES6 特性).考虑以下示例.

Best option is to use arrow function (ES6 feature). Consider following example.

addPet = () => {
 // Your awesome logic goes here  
}

这篇关于如何使用本机反应在控制台中打印状态?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆