首页 > 解决方案 > 为什么 onpress 功能在本机反应中不起作用

问题描述

类文件

 export class salon extends Component {

    constructor(props) {
    super(props);
    this.state = {
      status : true,
      };  
    }

     _toggleModal(){
     Alert.alert('hello');
     }

}

我在边栏中使用导航选项

我在可触摸的不透明度中添加了 onpress 功能,它不能仅触摸

 <TouchableOpacity onPress={() =>  {this._toggleModal}}>
 </TouchableOpacity>

标签: reactjsreact-nativereact-native-navigation

解决方案


您应该在构造函数或使用中绑定您的函数。

在构造函数中:

export class salon extends Component {
    constructor(props) {
       super(props);
       this.state = {
           status : true,
       };  
       this._toggleModal = this._toggleModal.bind(this);
    }

     _toggleModal(){
     Alert.alert('hello');
     }
}

正在使用:

 <TouchableOpacity 
     onPress={() =>  {this._toggleModal.bind(this)}}>
 </TouchableOpacity>

查看文档以获取更多信息。


推荐阅读