state undefined during onPress

在使用 RN 做登录页面的时候,碰到了一个坑

在0.47的文档里,RN 的 Button 示例是这样的:

class MyButton extends Component {
  _onPressButton() {
    console.log("You tapped the button!");
  }

  render() {
    return (
      <TouchableHighlight onPress={this._onPressButton}>
        <Text>Button</Text>
      </TouchableHighlight>
    );
  }
}

然而,这个示例有一个遗漏,这会造成一个坑。
如果你真这么写了,你的程序确实可以 build 可以run,但如果你要在_onPressButton里获取 state 的值,那么就会报错。

比如你的代码是这样的:

class MyButton extends Component {
    constructor(props) {
        super(props);
        this.state = {
            username: '',
            password: '',
        };
    }

  _onPressButton() {
    console.log("You tapped the button!");
    console.log("username: " + this.state.username);
    console.log("password: " + this.state.password);
  }

  render() {
    return (
      <TouchableHighlight onPress={this._onPressButton}>
        <Text>Button</Text>
      </TouchableHighlight>
    );
  }
}

那么当你按 Button 的时候你会得到这个:


image.png

究其原因,其实是绑定问题。
ES5自动对所有做了绑定,但是ES6没有做自动绑定,因此你需要手动绑定:

ES6 classes lose the autobinding you may have been used to with es5 react.createClass. You have to be more conscious of your binding when using ES6 for react components.

要解决这个问题,就需要绑定
你可以这样写:

      <TouchableHighlight onPress={this._onPressButton.bind(this)}>

也可以在 constructor 里设置:

  constructor(props) {
    super(props);
    this.state = {
      username: '',
      password: ''
    };

    this._onPressLogin = this._onPressLogin.bind(this)
  }

ES6标准写法:

<TouchableHighlight onPress={() => _onPressButton()}>

ES7标准写法:

_onPressButton = () => {
    console.log("You tapped the button!");
    console.log("username: " + this.state.username);
    console.log("password: " + this.state.password);
};

参考资料:

stackoverflow

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容