this.x不是一个函数

时间:2018-05-15 16:01:10

标签: javascript reactjs react-native

我在类和onPress处理程序中有一个方法,但似乎没有用。 起初onPress={() => this.logOut()}写得像这样:onPress={this.logOut}我认为应该是这样的,但按钮不能按这种方式按下。所以我尝试将其更改为onPress={() => this.logOut()},现在我可以按下按钮,但之后出现错误:Unhandled JS Exception: _this2.logOut is not a function

代码:

class Menu extends Component {

  constructor(props) {
    super(props);

  }

  logout = () => {
    AsyncStorage.getItem('user')
    .then((res) => {
      res = JSON.parse(res)
      res.token = null
      AsyncStorage.setItem('user', JSON.stringify(res))
      console.log('log out')
    })
    .done();
  }




  render() {
    return (
      <ScrollView scrollsToTop={false} style={styles.menu}>


        <TouchableHighlight style={styles.button} onPress={() => this.logOut()}>
          <Text style={styles.buttonText}>logout</Text>
        </TouchableHighlight>

      </ScrollView>
    );
  }
}


export default Menu;

0 个答案:

没有答案
相关问题